"How may I direct your message?"
If an object receives a message, then Ruby looks for a receiver of the same name, in this order:
... and so on
This chain ends with Object
, which mixes in Kernel
, and finally BasicObject
(which has no mixins)
Check out the ancestors
class method
>> String.ancestors
=> [String, Comparable, Object, Kernel, BasicObject]
Schematically:
class BasicObject
end
class Object < BasicObject
include Kernel
end
class String < Object
include Comparable
end
super
jumps up and calls the next method with the same name as this onesuper
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
super
callmethod_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
class Thing
def method_missing method_name, *args
puts method_name.to_s.reverse
args.reverse
end
end
t = Thing.new
t.whatever "hee", "haw"
revetahw
=> ["haw", "hee"]
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
def x.method_missing(name)
if (name == :hee)
puts "HAW!"
else
super
end
end
/