Ruby’s include operation mixes a module into a class or singleton class, placing the module in the method-lookup path. When included in an object’s singleton class, its methods are found before methods from the object’s original class. section 13.1.3
Overriding one object’s behavior
class C def talk puts "Hi from original class!" end end module M def talk puts "Hello from module!" end end c = C.new c.talk class << c include M end c.talk The calls print "Hi from original class!" and then "Hello from module!" because M is searched before C for c. section 13.1.3
Use the lookup path to distinguish the two common placements:
- Including a module in a regular class makes its methods available to instances of that class. section 13.1.3
- Including a module in a singleton class changes only that object’s behavior and gives the module precedence over the original class. section 13.1.3
- Call ancestors to inspect the classes and modules in the resulting method-lookup path. section 13.1.3
Figure 13.1 Method-search order, revised to include singleton classes
Trace the revised method-search order, including singleton classes and mixed-in modules. section 13.1.3
