Ben, when you call a method (say hello ) in Ruby, this happens:
- If the eigenclass receiver has a method called
hello , it will be called. If not: - If the receiver class has an instance method called
hello , it will be called. If not: - If any module included in the receiver class has an instance method called
hello , it will be called. If there are more than one, the last module will βwinβ. Otherwise: - If the superclass of the receiver class has an instance method called
hello , it will be called. If not: - If any module is included in the superclass of the receiver class ...
- (And so on for the superclass of the superclass, up to BasicObject ...)
- If no method named
hello , the same process is repeated using method_missing , starting with eigenclass, then the class, then the modules are turned on, then the superclass, then the modules included by the superclass ... this search is always successful, because Kernel determines the implementation by default method_missing .
So, to answer your question, if there is more than one method called hello , you cannot choose which one will be called. The method search rules described above determine which one will be called.
HOWEVER: Ruby is a very flexible language, and if you post more details about what you want to do and why, I can probably help you come up with a way to simulate the desired effect.
Another point: if you want to add class methods from a module to a class, you can do this:
module B; def hello; "hello B"; end end A.extend(B) A.hello => "hello B"
You see? When the include class is a module, the instance methods of the module become instances of the class in the class. When the extend class is a module, the instance methods of the module become class methods of the class.
source share