Knowing Self

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

  # class method
  def self.stuff
    puts "Inside class method"
    puts self

  # instance method
  def stuff
    puts "Inside instance method"	  
    puts self

# calling the class method (and module)

# calling the class method
c =

# singleton method
def c.stuff_it
  puts "Inside singleton method"
  puts self #instance C

#calling the singleton method

# Self as the default receiver of messages
class B
  def self.no_dot
    puts "self no dot"

  #no need to explicitly specify self.no_dot - self is the default receiver of no_dot message

And here is the output:

Inside module C:
Inside class met
Inside instance
Inside singleton
self no dot