×

ruby · level 3 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.