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:
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 mainclass/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.