ruby · level 3 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Procs and symbols as blocks. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
add_delivery = proc { |price| price + 3 }
prices = [10, 5]
p prices.map(&add_delivery)
p ["tea", "jam"].map(&:upcase)
your turn
Your turn. Keep a discount and use it twice.
Choose how many pounds to take off in the first blank. In the second blank, hand the discount proc to map as a block, then press run.
fix it
The greetings never get stored. Fix the method.
- The error says
add_greetingwas given 0 arguments but wants 1. Where did the block go? - A block is not a normal argument. To catch it as a proc, the parameter needs a special mark.
- On line 2, change the parameter to
&block, then press run.
nailed it
you caught a block and kept it. :D
&blockcatches the attached block as a proc.- Run a stored proc any time with
.call. &turns a proc or a:symbolback into a block.
new words in your collection
- proc
- &block
This lesson isn’t saved. A free account remembers every lesson you finish.