0
0
RubyConceptBeginner · 3 min read

What is self in Ruby: Understanding the Current Object

self in Ruby refers to the current object that is executing the code. It helps you know which object is the context for method calls or variable access at any point in your program.
⚙️

How It Works

Think of self as a name tag that always points to the "you" in a conversation. In Ruby, when code runs, self tells you which object is currently "speaking" or running the code. This is important because Ruby methods and variables belong to objects, and self helps you know exactly which object you are working with.

For example, inside a class, self usually means the instance of that class (an object created from it). But inside a class method, self refers to the class itself. This way, Ruby keeps track of context so your code knows where to look for methods and variables.

💻

Example

This example shows how self changes meaning inside instance and class methods.

ruby
class Person
  def instance_method
    puts "Inside instance method, self is: #{self}"
  end

  def self.class_method
    puts "Inside class method, self is: #{self}"
  end
end

person = Person.new
person.instance_method
Person.class_method
Output
Inside instance method, self is: #<Person:0x000055b8c1a2f8a8> Inside class method, self is: Person
🎯

When to Use

Use self when you want to be clear about which object you are referring to, especially inside methods. It helps avoid confusion between local variables and method calls. For example, when setting an attribute inside a method, self.attribute = value makes sure you call the setter method instead of creating a local variable.

Also, use self to define class methods by prefixing the method name with self.. This tells Ruby the method belongs to the class itself, not instances.

Key Points

  • self always points to the current object running the code.
  • Inside instance methods, self is the instance (object).
  • Inside class methods, self is the class itself.
  • Use self to call setters or define class methods clearly.

Key Takeaways

self refers to the current object executing the code.
Inside instance methods, self is the object instance.
Inside class methods, self is the class itself.
Use self to distinguish method calls from local variables.
Prefix methods with self. to define class methods.