← Back to Ruby Course | Chapter 9: OOP | Lesson 7 of 7

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.
Syntax
ruby
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)

markup
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
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
  1. Trying to create an object of a module with Greetable.new, which is a NoMethodError because modules cannot be instantiated.
  2. Forgetting include Greetable and then calling greet, which raises NoMethodError.
  3. Relying on a method like name that the including class must define, so greet fails when it is missing.
Chapter Summary
  • Classes define objects, with initialize setting up new ones and instance methods giving them behavior.
  • attr_accessor creates getters and setters.
  • Inheritance and super reuse behavior, and modules and mixins are previewed.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.