Lesson 8 of 8 · 12 min

Modules, mixins and Enumerable

A module is a bundle of methods (and constants) that is not a class: you cannot make objects from it. Modules are used two ways.

As a namespace

module Geometry
  PI = 3.14159
  def self.circle_area(r) = PI * r * r
end

Geometry.circle_area(2)

As a mixin

include a module in a class and its methods become methods of that class. This shares behaviour between classes that are otherwise unrelated:

module Greetable
  def greet = "Hello from #{name}"
end

class Robot
  include Greetable
  attr_reader :name
  def initialize(name) = @name = name
end

Robot.new("R2").greet   # "Hello from R2"

Enumerable

Ruby's most famous mixin is Enumerable. Define one method, each, include Enumerable, and your class gets map, select, sort_by, min_by, sum, count, first, include? and dozens more for free:

class Basket
  include Enumerable
  def initialize = @items = []
  def add(item) = @items << item
  def each(&block) = @items.each(&block)
end

&block captures the block passed to each and hands it on.

Your task

The starter has a Song class.

  1. Write module Describable with a describe method returning "Song: Neria (4:20)": the class name, a colon, and to_s. Include it in Song.
  2. Make Playlist include Enumerable by defining each, so map, select and sort_by work on playlists.
main.rb
class Song
  attr_reader :title, :seconds

  def initialize(title, seconds)
    @title = title
    @seconds = seconds
  end

  def to_s
    format("%s (%d:%02d)", title, seconds / 60, seconds % 60)
  end
end

class Playlist
  def initialize
    @songs = []
  end

  def add(song)
    @songs << song
  end
end

Ruby 3.4 runs right here in your browser. The first run downloads about 16 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…