Archive for December, 2009:
Method dispatch in Ruby
Some days ago I was asked how the dispatcher works in ruby and I was caught in surprise I didn’t know how to explain the method dispatching in the language we love (Ruby). That question was kept still in my mind for a few days but while listening to some workmates discussing about singleton classes in ruby the answer came to my mind in a blink of eyes reminding me from a university class which I had a long time ago about how method dispatching works in dynamic languages like Ruby.
So with that information in mind and some googling to confirm it I came out with a simple explanation of how the dispatching works in Ruby and decided it’s worth sharing you.
Essentially for each method call in ruby, the language interpreter checks in the inheritance hierarchy of the classes of the receiver (in our case “my_string“) to determine which method should be executed.
An example:
my_string = Hash.new # => {} my_string.size # => 0
The code above is pretty simple but what’s important is happening beneath of it. The language interpreter is assigning the variable “my_string” with an instance of the Hash class then it’s calling the method “size”.
The Hash class is where our interpreter will start searching for the “size” method, if the interpreter doesn’t find the method in the Hash class, it’ll continue to search in the Hash parent class, which in our case (Ruby) is the topmost class . It can be the case the interpreter don’t find the method “size”, so it’ll throw a “method missing” exception. In our example, the Hash class contains the “size” method and successfully returns.
If you want to know how MRI’s (Matz’s Ruby Interpreter) implements method dispatch, I recommend you to take a look in this blog post by Patrick Farley, where he explains the Ruby source code responsible for handling method dispatch.
For even further information on this matter there is this huge and excelent post from Russ Olsen, author of the book Design Patterns in Ruby.

