The Rules of Ruby Self

April 17, 2008

At the NovaRUG meeting yesterday, Dave Thomas gave a great talk on how the object model works in Ruby. One of his main points was that in Ruby you are always sending a message to an object. If you don't explicitly say which object you want to send the message to, Ruby sends it to self. In order to make Ruby as clear a language as it is, self changes during the execution of your code. To mentally keep track of what self is, you only need to understand rules of how self changes. There are only 2 things that change what self points to:

  1. Explicit receiver of method call

    puts self #self is "main", the top-level object instance
    Object.new  #self is temporarily changed to the class Object, but then back to main
    
  2. class/module definition

    puts self #Again, self is "main"
    class Foo
      puts self #self is now Foo
    end
    #self is back to being main
    

If you think of it this way, it should be easy to always figure out what self is pointing to. Being able to hold the mental picture of the changes to self as you read through code can make it easily to follow what is going on.

Posted in Technology | Tags Ruby

Comments Comments Feed

1. It's not strictly true it only happens in two cases. instance_eval and class_eval also change self:

class Test
end

p self
Test.new.instance_eval do
p self
end

Though these ones are fairly obvious, beware of the situations where people do "some_object.instance_eval { yield }" behind your back, as "self" may not be what you think it should be within a block you pass to a method.

# Posted By Vidar Hokstad on Friday, April 18 2008 at 8:44 AM

2. @Vidar

In that example the explicit receiver of the instance_eval method call is the new Test instance returned by Test.new, so that still falls under Rule #1.

# Posted By Paul Barry on Friday, April 18 2008 at 10:37 AM

3. I was actually doing research on calling self in an instance method vs a class method, and found this.

This examples shows "sending messages", but as a newbie I'm having hard time figuring out when you would just call self

# Posted By Randy on Thursday, July 8 2010 at 9:26 PM

Comments Disabled