Modules and Mixins (Preview)
A module is a bundle of helpful actions that many classes can share, like a skill card handed out to different characters. This preview shows how modules are mixed into classes.
In this page:
Syntax
module ModuleName
def method_name
# body
end
end
class ClassName
include ModuleName
end
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Trying to create an object of a module with
Greetable.new, which is aNoMethodErrorbecause modules cannot be instantiated. - Forgetting
include Greetableand then callinggreet, which raisesNoMethodError. - Relying on a method like
namethat the including class must define, sogreetfails when it is missing.
Chapter Summary
- Classes define objects, with
initializesetting up new ones and instance methods giving them behavior. attr_accessorcreates getters and setters.- Inheritance and
superreuse behavior, and modules and mixins are previewed.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: