Give a class a shared method
Define `module Greeting; def greet; puts "Hello!"; end; end`, then `class Greeter; include Greeting; end`. `Greeter.new.greet` prints `Hello!`, even though `greet` is not defined in `Greeter`. section 4.1
A mixin is a module incorporated into a class so its instance methods are available to that class’s instances. Modules cannot be instantiated. `include` mixes one in; `prepend` and `extend` are other ways to incorporate modules. Unlike a class, which has only one superclass, a class can mix in multiple modules. section 4.1
Listing 4.7 Two same-named methods on a single search path
module InterestBearing
def calculate_interest
puts "Placeholder! We're in module InterestBearing."
end
end
class BankAccount
include InterestBearing
def calculate_interest
puts "Placeholder! We're in class BankAccount."
puts "And we're overriding the calculate_interest method..."
puts "which was defined in the InterestBearing module."
end
end
account = BankAccount.new
account.calculate_interest
Run the example to see a class method win over a same-named method in its mixin. Method lookup takes the first match on the object’s search path. section 4.2.2
When multiple included modules define the same method, the most recently included module is searched first. Inclusion can also be nested: a module may include other modules. Avoid accidental name clashes, which make the winning method harder to spot. section 4.2.2
Choose between a mixin and inheritance according to what the code represents and may need later:
- Use a class for an entity that needs instances; use a module for a characteristic or shared behavior. section 4.4.1
- A mixin can supply behavior without using the class’s one superclass relationship. Do not split behavior into modules merely because it might someday be reused. section 4.4 section 4.4.1



