0
0
Rubyprogramming~5 mins

Self keyword behavior in Ruby

Choose your learning style9 modes available
Introduction

The self keyword helps you know which object is currently running the code. It points to the current object.

When you want to call a method on the current object inside a class.
When you want to refer to the current object to set or get its attributes.
When you want to define class methods instead of instance methods.
When you want to clarify that a method belongs to the current object to avoid confusion.
When you want to return the current object from a method.
Syntax
Ruby
self

self always points to the object that is running the current method or code.

Inside instance methods, self is the instance (object) itself.

Examples
This prints the current object p because self inside who_am_i is the instance.
Ruby
class Person
  def who_am_i
    puts self
  end
end

p = Person.new
p.who_am_i
Here, self is the class itself, so this defines a class method.
Ruby
class Person
  def self.describe
    puts "I am a Person class"
  end
end

Person.describe
Using self.name= calls the setter method for name on the current object.
Ruby
class Person
  attr_accessor :name

  def initialize(name)
    self.name = name  # Using self to call setter method
  end
end

p = Person.new("Alice")
puts p.name
Sample Program

This program shows how self works inside instance methods and class methods.

Ruby
class Car
  attr_accessor :color

  def initialize(color)
    self.color = color
  end

  def show_self
    puts "This car is: #{self.color}"
    puts "Self is: #{self}"
  end

  def self.info
    puts "Cars have wheels"
    puts "Self inside class method is: #{self}"
  end
end

car = Car.new("red")
car.show_self
Car.info
OutputSuccess
Important Notes

Inside instance methods, self is the object you created from the class.

Inside class methods (defined with self.method_name), self is the class itself.

Using self helps Ruby know you want to call a method or set a value on the current object, not create a local variable.

Summary

self points to the current object running the code.

Inside instance methods, self is the instance (object).

Inside class methods, self is the class itself.