ruby · level 3 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
writes a family of methods from a list of names.
An order can be pending, paid, shipped or refunded. You want paid?, shipped? and friends, each a : a method that answers yes or no. Writing four nearly identical methods by hand is dull, and a fifth status means remembering to write a fifth method.
define_method creates a method while the program runs. Inside the class body, loop over the names and call define_method("#{name}?") with a block. The block becomes the new method's body, and because it is a closure, it can still see name from the loop.
class Order
STATUSES = ["pending", "paid", "shipped", "refunded"]
attr_reader :status
def initialize(status)
@status = status
end
STATUSES.each do |name|
define_method("#{name}?") { status == name }
end
end
order = Order.new("paid")
p order.paid?
p order.shipped?
p Order.instance_methods(false).sort instance_methods(false) lists the methods a class defines itself, so you can see the four new predicates.
guess first
Methods made with parameters. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Remote
["louder", "quieter"].each do |action|
define_method(action) do |steps|
"Volume #{action} by #{steps}"
end
end
end
remote = Remote.new
puts remote.louder(3)
puts remote.quieter(1)
puts remote.respond_to?(:mute)
your turn
Your turn. Add a size, and its predicate appears.
Add a one-word size of your own to the list, such as huge. Then make a shirt in any of the four sizes and press run.
fix it
The traffic light has no green?. Fix the loop.
- The error says there is no
green?. What name diddefgive the method instead? deftakes its name literally, so it madeshade?, and it cannot see theshadevariable either.- Replace
def shade?on line 7 withdefine_method("#{shade}?") do, then press run.
nailed it
you wrote code that writes methods. :D
define_methodcreates a method from a name and a block.- Loop over a list of names to build a family of methods.
- The block is a closure, so it sees the loop's variable.
new words in your collection
- predicate
- define_method
This lesson isn’t saved. A free account remembers every lesson you finish.