27 Jul 2010, 11:14

Tony Eichelberger (10 posts)

I am trying to understand how method definitions work in regard to the value of self. In the simple example of episode 3 where method one defines method two:

class Example
  puts "before #{self}"
  def one
    puts "one #{self}"
    def two
      puts "two #{self}"

e = Example.new

f = Example.new

self is actually the instance ‘e’ when one is called the first time. I was somewhat expecting the method definition of ‘two’ to go into the singleton class for ‘e’. But then I was able to call two on a new instance ‘f’. So, inside a class definition, will self always be the class when I use the ‘def’ keyword without an explicit receiver?


28 Jul 2010, 11:01

Tony Eichelberger (10 posts)

Ok, I went back to episode 1 and looked the the “concept of the current class” and realized I was thinking about method definitions the wrong way. Method definitions are put into the current open class. When using an explicit receiver, the current class changes to the singleton class of the object. With no explicit receiver, the current open class is used. The value of self at the time of a method def is not relevant.

  You must be logged in to comment