What's self?
September 29, 2021 in ruby

The Ruby interpreter executes each line inside an object - the self object. Here are some important rules regarding self.

  • self is constantly changing as a program executes.
  • Only one object can be self at a given time.
  • When you call a method, the receiver becomes self.
  • All instance variables are instance variables of self, and all methods without an explicit receiver are called on self.
  • As soon as you call a method on another object, that other object (receiver) becomes self.

At the top level, self is main, which is an instance of Object. As soon as a Ruby program starts, the Ruby interpreter creates an object called main and all subsequent code is executed in the context of this object. This context is also called top-level context.

puts self  # main
puts self.class  # class

In a class or module definition, the role of self is taken by the class or module itself.

puts self  # main

class Language
  puts self  # Language

  def compile
    puts self  # #<Language:0x00007fc7c191c9f0>
  end
end

ruby = Language.new
ruby.compile

When you call a method, Ruby looks up the method in the object’s ancestor chain, and then executes the method with the receiver as self.