Lesson 17 of 23 · Ruby 3.2
Share behavior with modules
Share one set of instance methods across classes with include.
Learn
A module can define methods for reuse. include makes its instance methods available to instances of the including class. Unlike a class, a module cannot create instances with new. A mixin is useful when several classes need behavior without sharing a superclass.
An included method runs on the receiving object. Named#label calls name on that same Product instance, so Product must supply a name method. Modules can also group constants under a namespace, but this example uses a module to share behavior.
Example
module Named
def label
"item: #{name}"
end
end
class Product
include Named
def name
"book"
end
end
puts Product.new.labelExperiment
Predict the labels for these objects. Add another Product to products and check how the shared method uses each object's state.
Predict both labels. Add a third class that includes Named and defines its own name method. Call label on its instance.