When you send a message to an object, the object executes the first method it finds on its method lookup path with the same name as the message. If it fails to find any such method, it raises a NoMethodError exception - unless you have provided the object with a method called method_missing. The method_missing method is passed the symbol of the non-existent method, an array of the arguments that were passed in the original call and any block passed to the original method.
method_missing is in part a safety net: It gives you a way to intercept unanswerable messages and handle them gracefully. See the example - p012zmm.rb below.
- class Dummy
- def method_missing(m, *args, &block)
- puts "There's no method called #{m} here -- please try again."
- end
- end
- Dummy.new.anything
The output is:
- >ruby p012zmm.rb
- There's no method called anything here -- please try again.
- >Exit code: 0
You are also responsible for maintaining the method_missing signature. It's possible to write a hook that captures only a missing method's name while ignoring its arguments and associated block.