Explain it simply
Blocks in plain language
A block is a piece of code you hand to a method right after calling it, written as { ... } or do ... end. It is like giving a waiter a note that says "when you get there, do this". The method decides when, how many times and with what values to read the note, and the keyword that reads it is yield.
This pattern runs through all of Ruby: each, map, File.open and Dir.mktmpdir all accept blocks. The author of the method writes the frame of the job (open, time, close) and leaves the middle part to the caller.
Problem → Why → Solution
The problem: the same wrapper pasted again and again
A script writes log lines such as "[log] ... finished" before and after every task. At first it was only two lines, so they were pasted around each task, and now there are ten copies. Changing the log format means editing ten places, and forgetting one makes the logs inconsistent.
Worse is a task that fails. If the writing-report line raises, the "finished" line below it is never reached, so the log looks as though the task started and never ended. It would be better to write the frame once and supply only the middle part for each task.
puts "[log] saving user"
puts " user saved"
puts "[log] saving user finished"
puts "[log] sending email"
puts " email sent"
puts "[log] sending email finished"
puts "[log] writing report"
raise "disk full" # the finished line below never runs
puts "[log] writing report finished"A block lets the frame live in one place
One method owns the frame (the start and finish log lines) and calls the work you pass as a block with yield in the middle. To change the frame you edit one method, and with an ensure the "finished" log appears even when the work fails. That is why opening files, taking locks and starting transactions all have block forms in Ruby.
Core concept: blocks, yield and closures
A block is written directly after a method call: { |x| x * 2 } for one line and do |x| ... end for several. A call can carry only one block, and a block is not an object by itself; it travels with the call as part of it. The yield inside the method runs that block, the arguments to yield become the block's parameters, and the value of the block's last expression comes back as the result of yield.
Calling yield when no block was given raises LocalJumpError ("no block given (yield)"). Guard against it with block_given?, and decide what to do without a block: return a default, or return an Enumerator. Writing &block in a method's parameter list makes Ruby convert the block into a Proc object, so you can store it or pass it on to another method, and using &proc at a call site converts it back into a block.
A block is a closure: it remembers the local variables around the place where it was written and can read and change them, even though the method that receives it cannot see those variables. That is why [3, 4, 5].each { |n| total += n } increases the outer total. A method written with def is the opposite: it starts a fresh scope and cannot see the surrounding locals. A block parameter with the same name as an outer variable becomes its own variable inside the block, and names after the ; in |i; x| are block-local too.
Control flow needs careful sorting. A next inside a block ends the current call of the block, and its value is the block's result. A break stops the whole method that yielded to the block, and its value becomes that method's result. A return leaves the method where the block was written, so a return inside an each block in a method such as find_first_even ends the entire method. Inside a lambda, return leaves only the lambda. If a Proc is called after the method that wrote it has finished, the return has nowhere to go and raises LocalJumpError.
| Keyword | Inside a block | Inside a lambda |
|---|---|---|
| next | Ends this call; its value is the block's result | Acts like return |
| break | Stops the whole method that yielded | Acts like return |
| return | Leaves the method where the block was written | Leaves only the lambda |
- Method call carries a block
- The method runs it with yield
- Block's last value comes back
- Block sees variables around it
The block's value is the result of yield, and the variables inside a block live in the scope where it was written.
General pattern
def method_name(arg)
return enum_for(:method_name, arg) unless block_given?
result = yield(arg) # run the caller's block with a value
result
end
method_name(1) { |value| value + 1 } # one-line block
method_name(1) do |value| # multi-line block
value + 1
endInside the method, block_given? guards the call and returns an Enumerator when there is no block, and yield calls the block and captures its result. The caller uses { } for one line and do ... end for several.
Example: yield, a closure and block_given? in with_banner
with_banner is a frame that runs a block between two banner lines and returns the block's result. It calls the block as yield(title.length) with one value, so the block's |width| receives it. Watch both the closure, where the block changes the outer total, and the call made without a block.
def with_banner(title)
return "no work given for #{title}" unless block_given?
puts "== #{title} =="
result = yield(title.length)
puts "== done =="
result
end
total = 0
answer = with_banner("totals") do |width|
[3, 4, 5].each { |n| total += n }
total * width
end
puts answer
puts total
puts with_banner("empty")Code breakdown
- Guard
return "no work given for #{title}" unless block_given?When the call carries no block, the method returns a string instead of yielding. Without this check the yield would raise LocalJumpError.
- yield with a value
result = yield(title.length)This runs the block and hands it title.length (6). The block's last expression becomes the result of yield and lands in result.
- The call with a block
answer = with_banner("totals") do |width|do |width| ... end is the block attached to the call. |width| receives the 6 that yield supplies, and answer gets whatever with_banner returns.
- A closure at work
[3, 4, 5].each { |n| total += n }This inner block increases the outer total variable. A block remembers the scope where it was written, so it changes the caller's total rather than anything inside with_banner.
- The block's value
total * widthThis is the block's last expression: 12 * 6 = 72, which becomes the result of yield, then with_banner's return value, and finally answer. That is why 72 appears in the output.
- No block given
puts with_banner("empty")With no block, block_given? is false and the method returns its string right at the top, so no banner lines print.
== totals ==
== done ==
72
12
no work given for empty- Call with_banner("totals") with a block
- block_given? passes; print the opening line
- yield(6) jumps into the block
- The block's last value (72) comes back
- Print the closing line and return 72
A block was passed
The frame prints, the block runs, its value is returned
No block was passed
block_given? is false: the guard returns early
&block, Proc and Symbol#to_proc
Writing &block as the last parameter of a method makes Ruby convert the given block into a Proc object. You can run it with block.call(...), and because a block's Proc is not a lambda, block.lambda? is false. Writing &block at a call site converts the Proc back into a block, so pass_along hands the block it received on to items.map. A symbol written as &:upcase works too, because Ruby builds a block from it with Symbol#to_proc. Note also that in Ruby 3.4 and later the first block parameter can simply be called it.
def apply_twice(value, &block)
p block.class # Proc
p block.lambda? # false
block.call(block.call(value))
end
p apply_twice(3) { |n| n * 2 } # 12
def pass_along(items, &block)
items.map(&block) # & turns the Proc back into a block
end
p pass_along([1, 2, 3]) { |n| n + 10 } # [11, 12, 13]
p %w[ruby blocks].map(&:upcase) # ["RUBY", "BLOCKS"]
p [1, 2, 3].map { it * 3 } # [3, 6, 9]
p [[1, 2], [3, 4]].map { |a, b| a * b } # [2, 12]Closures remember their surroundings
make_counter creates a count variable and returns the lambda -> { count += 1 }. Even after make_counter has finished, the lambda keeps count alive and increases it on every call, and since each call to make_counter creates a new count, first and second count independently. By contrast, no_access, written with def, cannot see the outer total and raises NameError; that is the key difference between a block and a method.
def make_counter
count = 0
-> { count += 1 }
end
first = make_counter
second = make_counter
first.call
first.call
p first.call # 3
p second.call # 1: each closure keeps its own count
total = 0
[1, 2, 3].each { |n| total += n } # a block can change an outer local
p total # 6
def no_access
total # a def starts with a clean scope
end
begin
no_access
rescue NameError => e
puts e.message # undefined local variable or method 'total' for main
end
x = 10
[1].each { |i; x| x = 99 } # |i; x| makes x local to the block
p x # 10return, next and break inside blocks
The code below demonstrates the table's rules one by one. The block in first_even does a return, so the whole first_even returns 4. next 0 closes this iteration with 0 and map carries on. break n * 10 stops the entire each and returns 30, replacing each's normal result ([1, 2, 3, 4]). In lambda_return only the lambda exits, so the method continues and returns its string, while in proc_return the whole method exits. Calling the Proc returned by make_proc later raises LocalJumpError, because the method it would return from no longer exists.
def first_even(numbers)
numbers.each do |n|
return n if n.even? # returns from first_even, not just the block
end
nil
end
p first_even([1, 3, 4, 6]) # 4
p [1, 2, 3, 4].map { |n| next 0 if n.odd?; n } # [0, 2, 0, 4]
p [1, 2, 3, 4].each { |n| break n * 10 if n == 3 } # 30
def lambda_return
l = -> { return :from_lambda }
value = l.call
"after lambda: #{value}"
end
p lambda_return # "after lambda: from_lambda"
def proc_return
pr = proc { return :from_proc }
pr.call
"never reached"
end
p proc_return # :from_proc
def make_proc = proc { return 1 }
begin
make_proc.call
rescue LocalJumpError => e
puts e.message # unexpected return
endNo block? Return an Enumerator
Ruby's own iterator methods return an Enumerator when called without a block: [1, 2].each and [1, 2].map behave that way. Your own each can do the same with return enum_for(:each) unless block_given?. The payoff is that an Enumerator can be pulled one value at a time with e.next, raises StopIteration at the end, and chains into methods such as with_index and each_slice. Include Enumerable and provide each, and sort, map, first and many more come for free.
class Bag
include Enumerable
def initialize(*items)
@items = items
end
def each
return enum_for(:each) unless block_given?
@items.each { |item| yield item }
self
end
end
bag = Bag.new(3, 1, 2)
e = bag.each
p e.class # Enumerator
p e.next, e.next, e.next # 3, 1, 2
begin
e.next
rescue StopIteration => ex
puts ex.message # iteration reached an end
end
p bag.sort # [1, 2, 3]
p bag.map { |n| n * 2 } # [6, 2, 4]
p bag.each_slice(2).to_a # [[3, 1], [2]]
p bag.each.with_index(1).to_a # [[3, 1], [1, 2], [2, 3]]In real projects
Where this shows up in real projects
About half of everyday Ruby is blocks. each, map and select frame collections, File.open and Dir.mktmpdir frame resources, Mutex#synchronize frames thread safety, and Rails's transaction do frames the database, all with a block. Test frameworks build describe ... do and it ... do, Rake builds task :build do, and a Gemfile builds group :test do, all as DSLs made of blocks.
You can use the idiom in your own code: write methods named with_timing, with_retries or with_transaction that own the frame of a job and guarantee clean-up with ensure. Be careful, though: control flow gets hard to read inside deeply nested callback blocks, so keep blocks short and move longer ones into a named method. Also take care with return inside a block, because it leaves the whole method where the block was written.
Common mistakes
Common mistakes
1. Yielding when no block was given
Calling need after def need; yield; end raises LocalJumpError with the message "no block given (yield)". Check block_given? before yielding, or choose to return an Enumerator or a default value.
2. The precedence difference between { } and do ... end
do ... end binds more loosely than { }, so in p [1, 2, 3].map do |x| x * 2 end the block attaches to p, not to map. The output is #<Enumerator: [1, 2, 3]:map> instead of [2, 4, 6]. Using braces, as in p([1, 2, 3].map { |x| x * 2 }), or assigning the result to a variable first (result = [1, 2, 3].map do ... end) is safe.
3. Forgetting that the last expression is the result
[1, 2, 3].map { |x| puts x } returns [nil, nil, nil], because puts returns nil. Put the value you want on the last line of the block, and when you only want to print, use each instead of map.
4. A return inside a block leaving the whole method
A return inside each does not just skip this iteration; it leaves the entire method and the remaining code never runs. Use next to skip only the current iteration. A stored Proc called later can raise LocalJumpError, so use a lambda (-> { }) for code you intend to keep.
Best practices
Best practices
- Use { } for one-line blocks and do ... end for multi-line ones, and prefer { } when you use the result.
- Check block_given? when the block is optional, and return an Enumerator from iterator-style methods.
- Keep the frame of a job (open and close, logging, locking) in one method and clean up with ensure.
- Keep blocks short, and move a long one into a named method.
Mini challenge
Mini challenge: an Inventory iterator
Write an Inventory class with an each_low method that yields items below a limit, and a restock method that adds whatever number the block returns.
- each_low(limit) yields the item name and quantity, and returns an Enumerator when no block is given
- restock(limit) yields every low item to the block and adds the number the block returns to its quantity
- to_s returns text such as "bolt=10, nut=10, gear=9"
- Print each_low(5) with a block, pull the names through the Enumerator, then restock(5) { |_name, qty| 10 - qty } and print the result
class Inventory
def initialize(stock)
@stock = stock
end
def each_low(limit)
# TODO: return an Enumerator when no block is given
# TODO: yield the name and quantity of every item below the limit
end
def restock(limit)
# TODO: for each low item, add the number the block returns
end
def to_s
# TODO: "bolt=10, nut=10, gear=9"
end
end
# TODO: build the inventory, print the low items, list their names, then restockExpected: Expected output: low: bolt (3) low: nut (1) ["bolt", "nut"] bolt=10, nut=10, gear=9
Show hint
Start with @stock.each { |name, qty| yield name, qty if qty < limit }. In restock, take each_low(limit).to_a first so you are not editing the hash while iterating it, and remember that the value of yield(name, qty) is what the block returned.
Show solution
class Inventory
def initialize(stock)
@stock = stock
end
def each_low(limit)
return enum_for(:each_low, limit) unless block_given?
@stock.each { |name, qty| yield name, qty if qty < limit }
end
def restock(limit)
each_low(limit).to_a.each do |name, qty|
@stock[name] = qty + yield(name, qty)
end
self
end
def to_s
@stock.map { |name, qty| "#{name}=#{qty}" }.join(", ")
end
end
inventory = Inventory.new("bolt" => 3, "nut" => 1, "gear" => 9)
inventory.each_low(5) { |name, qty| puts "low: #{name} (#{qty})" }
p inventory.each_low(5).map { |name, _qty| name }
inventory.restock(5) { |_name, qty| 10 - qty }
puts inventoryQuick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Pass a block with { |x| ... } or do |x| ... end after a method call; the method runs it with yield, and the block's last value is the result of yield.
- Without a block, yield raises LocalJumpError, so check block_given? and, for iterators, return enum_for(...) unless block_given?.
- A block is a closure that remembers the surrounding local variables, a def method starts with a fresh scope, and &block converts a block into a Proc.
- Inside a block next leaves this iteration, break leaves the method that yielded and return leaves the method where the block was written, while return in a lambda leaves only the lambda.
Official Ruby Documentation — Ruby Documentation