×

ruby · level 3 · unit 1 · 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

A is a block you can keep for later.

A block normally vanishes once the method finishes. Put at the end of the parameters and Ruby catches the block as a proc: a block turned into an object. You can store it in a variable, an array or a hash, and run it whenever you like with .call.

This is how buttons work. You hand over what should happen now, and the button runs it later, when somebody clicks. You can also make a proc directly with proc { |price| price + 3 }.

The & works the other way too. In a method call, & turns a proc back into a block, so prices.map(&add_delivery) hands the proc to map. &:upcase is a shortcut for the block { |x| x.upcase }.

class Button
  def on_click(&block)
    @action = block
  end
  def click
    @action.call
  end
end
save = Button.new
save.on_click { puts "Saving your work..." }
puts "Nothing has happened yet."
save.click

The block does not run when it is attached, only when click calls the stored proc.