ruby · level 3 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
runs the block someone handed to your method.
You have used blocks with each and times since Level 1. Now you write the method on the other side. Inside your method, yield runs whatever block the caller attached, then your method carries on from the next line. It is like a recipe saying: now add your favourite topping.
yield can hand values to the block, and they arrive between its bars: yield(2.5, 3) fills |coffee, cake|. The block's last line comes back as the answer of yield, so your method can use it.
Calling yield when no block was attached crashes with . When the block is optional, ask first.
def receipt(shop)
puts "== #{shop} =="
total = yield(2.5, 3)
puts "Total: #{total}"
end
receipt("Corner Cafe") do |coffee, cake|
coffee + cake
end Curly braces { |word| ... } work like do and end, and most Rubyists use them for one-line blocks.
guess first
Two yields and a last line. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def twice
yield "first"
yield "second"
"done"
end
result = twice { |word| puts word.upcase }
puts result
your turn
Your turn. Make an announcer that takes a block.
Fill the first blank so the method runs the block and hands it name. Then type a winner's name in the second blank and press run.
fix it
The cake has no block, and the program falls over. Fix it.
- The tea line works. The cake call has no block. What does
yielddo then? - With no block attached,
yieldraises LocalJumpError. Only yield when there is a block. - Add
if block_given?to the end of line 3, then press run.
nailed it
your methods can take blocks now. :D
yieldruns the block the caller attached.- Values after
yieldarrive between the block's bars. - Check
block_given?when the block is optional.
new words in your collection
- yield
- block_given?
- LocalJumpError
This lesson isn’t saved. A free account remembers every lesson you finish.