Modules – toolboxes for code
A module is a named box for methods and constants. Unlike a class, a module cannot create objects (there is no new) – modules have two other jobs: keeping things organized and sharing abilities.
You already know some: Math from Ruby's standard library collects math tools. You reach constants with :: and call methods with a dot:
Math::PIMath.sqrt(49)Job 1 – namespace: A module groups related classes under one roof so names don't clash. That's exactly why the classes you'll meet in later lessons are called ChunkyPNG::Image and Sinatra::Base – class Image inside module ChunkyPNG, class Base inside module Sinatra:
module Forest
class Fox
def shout
"Chunky Bacon!"
end
end
end
Forest::Fox.new.shoutJob 2 – mixin: With include you mix a module's methods into a class – that way many classes can share an ability without inheriting from each other: (By the way, include too is just a method call without parentheses.)
module Greeting
def hello
"Hello, I am #{name}!"
end
end
class Hedgehog
include Greeting
attr_reader :name
def initialize(name)
@name = name
end
end
Hedgehog.new("Izzy").helloWhere does the module sit now? ancestors from lesson 44 tells you. Ruby looks for a method in exactly this order: first in the class itself, then in the mixed-in modules, then in the parent class:
Hedgehog.ancestors.first(3)Ruby's most famous mixins work the same way. You know Enumerable from lesson 13 already: it gives a class map, select & co. as soon as it can each – arrays, hashes and ranges have it mixed in. Comparable gives a class <, >, between? and clamp as soon as it can <=> – the “spaceship operator”, which returns -1, 0 or 1 depending on whether an object is smaller than, equal to or greater than another:
class Parcel
include Comparable
attr_reader :weight
def initialize(weight)
@weight = weight
end
def <=>(other)
weight <=> other.weight
end
end
light = Parcel.new(2)
heavy = Parcel.new(5)
[light < heavy, Parcel.new(3).between?(light, heavy), [heavy, light].min.weight]One single method, <=> – and in return Ruby gives you six comparisons, plus sort, min and max for lists of your objects. That's the power of mixins.
Loud with a method shout that returns CHUNKY BACON!. Mix it into a new class Badger with include and try Badger.new.shout as the last line.# module Loud
# ...
# end
# class Badger
# ...
# end
Backpack comparable, like the parcel above: include Comparable, an attr_reader :weight, an initialize(weight) and a <=> that compares the weights. Then Ruby can compare backpacks with < and find the lightest in an array with min – the last line should give 3.# class Backpack
# include ... # Comparable, by weight
# attr_reader :weight
# ...
# end
# [Backpack.new(7), Backpack.new(3), Backpack.new(5)].min.weight