liveBook · Manning

Include

As explained in The Well-Grounded Rubyist, Fourth Edition

Module inclusion is the Ruby mechanism that adds a module's instance methods to a class's method lookup chain.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains lookup precedence and ancestors inspection, contrasting singleton-class inclusion with regular-class inclusion.
Examples
Demonstrates Person objects, a Secretive module, singleton-class inclusion, method overriding, and ancestors output.
What it assumes
Assumes familiarity with Ruby classes, objects, modules, methods, and singleton classes.
What you can do after
Apply include to alter class-wide or single-object method behavior and inspect the resulting lookup path.
How it connects
Connects modules with classes, singleton classes, method lookup, inheritance, and the ancestors method.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.