typestar

Modules and mixins in Ruby

Sharing behavior across classes without inheritance.

# a module holds behavior; include mixes it into any class
module Greetable
  def greet
    "hi, I am #{display_name}"
  end
end

class Robot
  include Greetable

  def initialize(id)
    @id = id
  end

  def display_name
    "unit-#{@id}"
  end
end

puts Robot.new(7).greet

How it works

  1. A module defines methods with no class of their own.
  2. include mixes the module into a class as instance methods.
  3. The mixin calls display_name, which the host class provides.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
249
Tokens
45
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 32 seconds.

Type this snippet

Step 3 of 3 in Classes & modules, step 21 of 29 in Language basics.

← Previous Next →