×

ruby · level 3 · unit 1 · lesson 1

  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

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.