Modules and Mixins (Preview)
In this page:
Modules and Mixins (Preview)
A module groups related methods and constants together without being instantiable itself, and can be mixed into a class with include to share behavior across unrelated classes -- Ruby's alternative to multiple inheritance. This is previewed here and covered in full detail in the next chapter. Mixins are a defining feature of idiomatic Ruby object design.
Note: A module included into a class effectively inserts itself into that class's method lookup chain.
Example: Modules and Mixins (Preview)
module Greetable
def greet
puts "Hello, I'm #{name}"
end
end
class Person
include Greetable
attr_reader :name
def initialize(name)
@name = name
end
end
Person.new("Alice").greet
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: