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

Modules and Mixins (Preview)

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
🔒

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.