Ruby Module Methods
Some modules work as toolboxes rather than mix-ins. Their methods run through the module name, and no object is built from the module.
A toolbox with module_function
module_function sits above the methods of Calculator. Both methods then answer through the Calculator name.
module Calculator
module_function
def double(number)
number * 2
end
def square(number)
number * number
end
end
puts Calculator.double(4)
puts Calculator.square(3)The same job with extend self
Shouter extends itself with extend self. Its methods answer through the Shouter name, just like the toolbox above.
module Shouter
extend self
def shout(text)
text.upcase
end
def whisper(text)
text.downcase
end
end
puts Shouter.shout("hello")
puts Shouter.whisper("LOUD")Methods with def self.
Formatter defines each method with def self. in front of its name. Each method belongs to the Formatter module itself.
module Formatter
def self.bracket(text)
"[#{text}]"
end
def self.shout(text)
text.upcase
end
end
puts Formatter.bracket("note")
puts Formatter.shout("note")Example
module Temperature
module_function
def to_fahrenheit(celsius)
celsius * 9 / 5 + 32
end
def to_celsius(fahrenheit)
(fahrenheit - 32) * 5 / 9
end
end
puts Temperature.to_fahrenheit(20)
puts Temperature.to_celsius(68)Key points
- module_function makes the methods after it callable on the module.
- A toolbox call joins the module name and the method name with a dot.
- extend self inside a module gives the same call shape.
- def self. before a method name defines that method on the module itself.
- All three routes let a program call a method through the module name.
In this example, Temperature is a toolbox module with module_function above its methods. to_fahrenheit turns 20 degrees into 68, and to_celsius turns 68 back into 20. Both calls go through the Temperature name.
Note
A toolbox module is called through its name, so nothing calls new on it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line makes the methods after it callable through the module name?