TExcelTAD
Home › Ruby › Ruby Blocks & yield

Ruby Blocks & yield

Blocks are the heart of Ruby. You have already used them with each, map and times. In this lesson you'll learn to write your own methods that accept a block, using the keyword yield.

A block is code passed to a method

Any method call can be followed by a block. The method decides when — and whether — to run it:

ruby · try it yourself
def twice
  yield
  yield
end

twice { puts "Hip hip hooray!" }
Hip hip hooray!
Hip hip hooray!

yield means "run the block the caller gave me, right here".

Passing values into the block

Arguments given to yield become the block's parameters:

ruby · try it yourself
def each_weekday
  %w[Mon Tue Wed Thu Fri].each_with_index do |day, i|
    yield day, i + 1
  end
end

each_weekday { |day, number| puts "#{number}: #{day}" }
1: Mon
2: Tue
3: Wed
4: Thu
5: Fri

Getting a value back from the block

The value of the block's last expression is returned by yield. That's how map and select work — and you can build the same thing:

ruby · try it yourself
def my_map(items)
  result = []
  items.each { |item| result << yield(item) }
  result
end

def my_select(items)
  result = []
  items.each { |item| result << item if yield(item) }
  result
end

p my_map([1, 2, 3]) { |n| n * 100 }
p my_select(%w[ant bear cat]) { |w| w.length == 3 }
[100, 200, 300]
["ant", "cat"]

block_given?

Calling yield without a block raises LocalJumpError. Use block_given? to make the block optional:

ruby · try it yourself
def greet(name)
  if block_given?
    yield name
  else
    "Hello, #{name}"
  end
end

p greet("Tom")
p greet("Tom") { |n| "Yo #{n}!" }
"Hello, Tom"
"Yo Tom!"

Blocks are closures

A block can read and change the local variables around it, even though it runs inside another method:

ruby · try it yourself
total = 0
count = 0
[15, 25, 40].each do |price|
  total += price
  count += 1
end
puts "#{count} items, total #{total}"
3 items, total 80

This ability to "close over" surrounding variables is why blocks are called closures.

Block parameters are local to the block. If you need a block-local variable that shadows an outer one on purpose, list it after a semicolon: { |x; tmp| ... }.

Setup and teardown around a block

A very common pattern: the method prepares something, yields, then cleans up — no matter what the block did. File.open with a block works this way (it closes the file automatically).

ruby · try it yourself
def with_timer_label(label)
  puts "-- start #{label}"
  result = yield
  puts "-- end #{label}"
  result
end

value = with_timer_label("sum") do
  (1..1000).sum
end
p value
-- start sum
-- end sum
500500
ruby · try it yourself
def html_tag(name)
  "<#{name}>#{yield}</#{name}>"
end

puts html_tag("p") { "Hello " + html_tag("b") { "world" } }
<p>Hello <b>world</b></p>

Explicit block parameter: &block

Instead of yield, you can capture the block as an object with &block and call it with .call. That's useful when you want to store it or pass it to another method:

ruby · try it yourself
class Button
  def initialize(label)
    @label = label
    @handlers = []
  end

  def on_click(&handler)
    @handlers << handler
  end

  def click
    @handlers.each { |h| h.call(@label) }
  end
end

button = Button.new("Save")
button.on_click { |label| puts "#{label} clicked" }
button.on_click { |label| puts "Logging: #{label.downcase}" }
button.click
Save clicked
Logging: save

Numbered and it parameters

For tiny blocks, Ruby offers implicit parameters. _1, _2 refer to the block's arguments by position, and Ruby 3.4 adds it for a single argument:

ruby · try it yourself
p [1, 2, 3].map { it * 10 }
p %w[x y].each_with_index.map { "#{_1}#{_2}" }
p [[1, 2], [3, 4]].map { _1 + _2 }
[10, 20, 30]
["x0", "y1"]
[3, 7]

{ } vs do...end

Both create a block. The only technical difference is precedence: {} binds to the nearest method call, do...end to the outermost one. This matters when you leave out parentheses:

ruby
puts [1, 2].map { |n| n * 2 }      # prints 2 and 4
puts [1, 2].map do |n| n * 2 end   # block goes to puts! prints an Enumerator

Tip: Use { } for short single-line blocks that return a value, and do ... end for multi-line blocks that do work.

Test yourself

What does yield do inside a method?

  1. Returns from the method
  2. Runs the block passed to the method
  3. Pauses the program
  4. Creates a new thread

How can a method check whether it received a block?

  1. block?
  2. yield?
  3. block_given?
  4. defined?(block)

What is the value of yield(5) if the block is { |n| n + 1 }?

  1. 5
  2. 6
  3. nil
  4. true