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.
- Write
module Describablewith adescribemethod returning"Song: Neria (4:20)": the class name, a colon, andto_s. Include it inSong. - Make
PlaylistincludeEnumerableby definingeach, somap,selectandsort_bywork on playlists.