ruby · level 2 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A keeps related tools together under one name.
Some methods belong together but need no objects, like money helpers. Put them in a module: module Money, the methods, then end. Write each method as def self.pounds(pence), and call it with the module's name: Money.pounds(250).
A is a value that should never change, written in capitals, like VAT = 0.2. Reach a module's constant with two colons: Money::VAT. Ruby's own Math module works the same way, with Math.sqrt(16) and Math::PI.
module Money
VAT = 0.2
def self.pounds(pence)
format("£%.2f", pence / 100.0)
end
end
puts Money.pounds(250)
puts Money::VAT
puts Math.sqrt(16)
puts Math::PI.round(2) self. in front of a method's name means the method belongs to the module itself.
guess first
Fence in the garden. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
module Garden
FENCE_COST = 12
def self.fence(length, width)
(length + width) * 2 * FENCE_COST
end
end
puts Garden.fence(5, 3)
puts Garden::FENCE_COST
your turn
Your turn. Build a temperature tool.
Pick a temperature in Celsius, then press run to convert it to Fahrenheit with the module.
fix it
Ruby cannot find the module's method. Can you fix it?
- Read the error. Ruby says the module has no method called
hello, yet you wrote one. What is missing? - To call a method on the module itself, its name needs
self.in front. - Change line 2 to def self.hello(name), then press run.
nailed it
you packed your tools into a module. :D
- A module groups methods and constants under one name.
def self.poundsmakes a method you call asMoney.pounds.- Constants are in capitals. Reach them with
Money::VAT.
new words in your collection
- module
- constant
This lesson isn’t saved. A free account remembers every lesson you finish.