Blocks, Procs and Lambdas
Blocks are Ruby’s signature feature: they let a method receive behaviour, not just data, which is why
each, File.open and Rails migrations read like syntax. Procs and lambdas are the same idea reified
— closures you can store and pass around.
The 60-second answer
Section titled “The 60-second answer”A block is an anonymous chunk of code attached to a method call. The method invokes it with
yield, checks for it withblock_given?, or captures it with&block. A proc is a block turned into an object; a lambda is a proc with method-like semantics.returninside a lambda returns from the lambda, while inside a proc it returns from the enclosing method — and lambdas enforce arity while procs do not. All of them are closures, capturing local variables from where they were defined.
Blocks
Section titled “Blocks”[1, 2, 3].map { |n| n * 2 } # braces for value-returning one-liners
[1, 2, 3].each do |n| # do...end for side effects puts nend
# Precedence: braces bind to the innermost call, do...end to the outermostputs [1, 2].map { |n| n * 2 } # prints [2, 4]puts [1, 2].map do |n| n * 2 end # prints an Enumerator, block not calledyield and block_given?
Section titled “yield and block_given?”def maybe_yield return "no block" unless block_given? yield(1, 2)end
maybe_yield # => "no block"maybe_yield { |a, b| a + b } # => 3yield without a block raises LocalJumpError: no block given (yield) — which is why block_given? exists.
Procs and lambdas
Section titled “Procs and lambdas”square = proc { |x| x * x }square.call(4) # => 16 (also square.(4) and square[4])
lenient = proc { |a, b| [a, b] }lenient.call(1) # => [1, nil]lenient.call(1, 2, 3) # => [1, 2] — extras discarded
strict = ->(a, b) { [a, b] }strict.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)The two real differences
Section titled “The two real differences”def with_lambda l = -> { return :from_lambda } l.call :after_lambda # reachedendwith_lambda # => :after_lambda
def with_proc p_ = proc { return :from_proc } p_.call :after_proc # never reachedendwith_proc # => :from_procA proc’s return is the enclosing method’s return; if that method already returned, calling the
proc raises LocalJumpError. That is the classic “why did my callback abort the method” bug.
| Behaviour | Proc | Lambda |
|---|---|---|
| Created with | proc {} / Proc.new {} |
->() {} / lambda {} |
return returns from |
enclosing method | the lambda |
| Arity check | lenient | strict |
lambda? |
false |
true |
| Class | Proc |
Proc |
Closures
Section titled “Closures”Every proc and lambda captures its defining scope, keeping variables alive after the method returns:
def counter; count = 0; -> { count += 1 }; end returns a counter that keeps its own count.
The captured variable is shared, not copied: two closures over the same count see each other’s
changes. Each block iteration gets a fresh binding for its parameters, so (1..3).map { |i| -> { i } }
captures 1, 2, 3 — unlike JavaScript with var, which is a classic interview contrast.
The & operator
Section titled “The & operator”& is two inverse operations: &block in a parameter list captures the block as a Proc, and &obj
in an argument list converts a Proc into a block (calling to_proc).
[1, 2, 3].map(&:to_s) # => ["1", "2", "3"] — Symbol#to_proc%w[a b].map(&:upcase) # => ["A", "B"]
def double(n) = n * 2[1, 2].map(&method(:double)) # => [2, 4]A captured block is always a proc (lambda? is false), even if the caller passed a lambda. And
Symbol#to_proc works because :upcase.to_proc is equivalent to
->(receiver, *args) { receiver.upcase(*args) }.
Follow-up questions
Section titled “Follow-up questions”- Why does a captured block report
lambda? == falseeven when passed with&? - What happens if a proc escapes its method and is called afterwards?
- How does
Symbol#to_procactually work? - What does
&nilmean in a parameter list?
Common traps
Section titled “Common traps”returnin a proc passed toeach. It returns from the whole method.- Assuming blocks are lambdas. Blocks are lenient and return from the enclosing method.
- Braces vs
do...endprecedence. Braces attach to the innermost call. - Forgetting
block_given?beforeyield.LocalJumpErrorat runtime.