Method Lookup
When Ruby evaluates a method invocation expression, it must
first figure out which method is to be invoked. The process for doing
this is called method lookup or method
name resolution. For the method invocation expression
o.m, Ruby performs name resolution
with the following steps:
First, it checks the eigenclass of
ofor singleton methods namedm.If no method
mis found in the eigenclass, Ruby searches the class ofofor an instance method namedm.If no method
mis found in the class, Ruby searches the instance methods of any modules included by the class ofo. If that class includes more than one module, then they are searched in the reverse of the order in which they were included. That is, the most recently included module is searched first.If no instance method
mis found in the class ofoor in its modules, then the search moves up the inheritance hierarchy to the superclass. Steps 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
mis found after completing the search, then a method namedmethod_missingis invoked instead. In order to find an appropriate definition of this method, the name resolution algorithm starts over at step 1. TheKernelmodule provides a default implementation ofmethod_missing, so this second pass of name resolution is guaranteed to succeed. Themethod_missingmethod is covered in more detail in Handling Undefined Methods.
Let’s consider ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access