Method Dispatching
Dot, the Dispatcher
"How may I direct your message?"
Method Lookup Order
If an object receives a message, then Ruby looks for a receiver of the same name, in this order:
- its singleton class
- its class
- its modules, in reverse order of inclusion
- its superclass
- its superclass' modules
... and so on
This chain ends with Object
, which mixes in Kernel
, and finally BasicObject
(which has no mixins)
ancestors
Check out the ancestors
class method
>> String.ancestors
=> [String, Comparable, Object, Kernel, BasicObject]
Schematically:
@@@ ruby
class BasicObject
end
class Object
include Kernel
end
class String
include Comparable
end
super
- Able to leap tall class inheritance hierarchies with a single bound
super
jumps up and calls the next method with the same name as this one
super (cont.)
super
with some arguments passes those argumentssuper
with no arguments passes the same arguments that were originally passed to this methodsuper()
with an empty argument list calls the parent method with no arguments- needed to resolve the ambiguity of the bareword
super
call
- needed to resolve the ambiguity of the bareword
method_missing
If method dispatch fails, then it starts all over again!
Only this time it's looking for a method named method_missing
Useful for "builder pattern" objects
Ref. WGR Section 4.3. The method_missing method
method_missing
+ super
From inside method_missing
, super
looks up the chain for another method_missing
method
Allows chaining/overriding of method_missing
calls, or fallback to NoMethodError