This is an attempt on consolidating my thoughts on Ruby’s self, taken from Well Grounded Rubyist chapter 5.
Another crucial point of Ruby to understand is the notion of self. Self is used to refer to the current object or the default object at a given time. At every point of your program there is one and only self.
Self inside Class and Module is straight forward. Self in method is also not too hard to understand, but you need to understand the context of the method.
Method can belong to class, self in method class will return the class object itself (remember that class IS object in Ruby). Method can belong to an instance of a class, self in that context will surprise2 return the instance. Method can be a singleton - in this case, calling self will also return the instance of a class.
Another point about self is: it is the default receiver of messages (see the code snippet below - it is explained there).
Below is code snippet that I hope illustrate the points above (stitched together from the examples in the book):
class C module M puts "Inside module C::M" puts self end # class method def self.stuff puts "Inside class method" puts self end # instance method def stuff puts "Inside instance method" puts self end end # calling the class method (and module) C.stuff C::M # calling the class method c = C.new c.stuff # singleton method def c.stuff_it puts "Inside singleton method" puts self #instance C end #calling the singleton method c.stuff_it # Self as the default receiver of messages class B def self.no_dot puts "self no dot" end #no need to explicitly specify self.no_dot - self is the default receiver of no_dot message no_dot end
And here is the output:
Inside module C: C::M Inside class met C Inside instance # Inside singleton # self no dot