- As the first step, Ruby checks the eigenclass of o for singleton method named m.
- If the method named m is not found in the eigenclass, Ruby search the class of o for an instance method name m.
- If the method m is not found in the class, Ruby searches the instance methods of any modules included by the class of o. If there are modules included, they searched in the reverse of the order which they are included.
- If no instance method m is found in the class of o or in its modules, then the search moves up the inheritance hierarchy of the super class. Step 2 and 3 are repeated for each class in the inheritance hierarchy until each ancestor class and its included modules have been searched.
- If no method named m is found after completing the search, then a method named method_missing is invoked instead. In order to find an appropriate definition of this method, the name resolution algorithm starts over at step 1. The Kernel module provides a default implementation of method_missing, so this second pass of name resolution is guaranteed to succeed.
test_str = "hello" test_str.world
- Check the eigenclass for singleton methods. There aren't any in this case.
- Check the String class. There is no instance method named world.
- Check the Comparable and Enumerable modules of the String class for an instance method named world. Neither module defines such a method.
- Check the superclass of String, which is Object. The Object class does not define a method named world, either.
- Check the Kernel module included by Object. The world method is not found here either, so we now switch to looking for a method named method_missing.
- Look for method_missing in each of the spots above (the eigenclass of the String object, the String class, the Comparable and Enumerable modules, the Object class, and the Kernel module). The first definition of method_missing we find is in the Kernel module, so this is the method we invoke. What it does is raise an exception: undefined method `hello' for "Hello":String (NoMethodError)
class Class def m p "Class#m" end end class A end class B < A end B.m # Prints out "Class#m" def A.m p "A.m" end B.m # Prints out "A.m"
Related posts brought to you by Yet Another Related Posts Plugin.



1 response so far ↓
1 coderrr // Aug 26, 2008 at 12:27 pm
check out my post on how constant name resolution in ruby works: http://coderrr.wordpress.com/2008/03/11/constant-name-resolution-in-ruby/
Leave a Comment