๐ŸŽ“ A1Learner
๐Ÿ”

Ruby Modules

A module is a box of shared methods. Classes that need those methods can mix them in with include.

One class mixes in a module

Greeter holds one greet method. Dog mixes Greeter in with include, so a dog object can call greet.

module Greeter
  def greet
    puts "Hello from the module"
  end
end
class Dog
  include Greeter
end
dog = Dog.new
dog.greet

Two classes share one module

Dog and Cat both include Greeter. greet reads the @name of the object that calls it, so each one prints its own name through the same method.

module Greeter
  def greet
    puts "#{@name} says hello"
  end
end
class Dog
  include Greeter
  def initialize(name)
    @name = name
  end
end
class Cat
  include Greeter
  def initialize(name)
    @name = name
  end
end
dog = Dog.new("Rex")
cat = Cat.new("Milo")
dog.greet
cat.greet

A module can hold more methods

Greeter holds greet and farewell here. The robot mixes in both methods with one include line.

module Greeter
  def greet
    puts "Hello"
  end
  def farewell
    puts "Goodbye"
  end
end
class Robot
  include Greeter
end
robot = Robot.new
robot.greet
robot.farewell

Example

module Greeter
  def greet
    puts "#{@name} says hello"
  end
  def farewell
    puts "#{@name} says goodbye"
  end
end
class Dog
  include Greeter
  def initialize(name)
    @name = name
  end
  def fetch
    puts "#{@name} fetches the ball"
  end
end
class Cat
  include Greeter
  def initialize(name)
    @name = name
  end
end
dog = Dog.new("Rex")
cat = Cat.new("Milo")
dog.greet
dog.fetch
cat.greet
cat.farewell

Key points

  • The word module starts a module, and the word end closes it.
  • include inside a class mixes the module methods into that class.
  • An object of the class can call the mixed-in methods as its own.
  • Many classes can include the same module.
  • A module alone cannot build objects with new.

In this example, Greeter holds greet and farewell. Dog and Cat both include Greeter, so their objects call the shared methods with their own names. fetch belongs to Dog alone.

Note

A class can include more than one module.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

What does include Greeter do inside a class?