Skip to content
Ruby

Blocks, Procs, Lambdas

Use blocks with yield, Procs, lambdas, and the & operator.

By EZ4Code Team
blockproclambda

Code

# Block - implicit, passed to a method call
[1, 2, 3].each { |n| puts n }
result = [1, 2, 3].map { |n| n * 2 }
puts result.inspect

# yield to caller's block
def repeat(n)
  n.times { yield }
end
repeat(3) { print "hi " }
puts

# Proc - explicit object wrapping a block
square = Proc.new { |x| x * x }
puts square.call(5)
puts square.(6)         # alternate call syntax

# Lambda - stricter arity, returns from itself not the caller
add = ->(a, b) { a + b }
puts add.call(1, 2)

# Method taking a block explicitly
def apply(a, b)
  yield(a, b)
end
puts apply(4, 5) { |x, y| x * y }

# & to convert block <-> proc
def capture(&blk); blk.call; end
capture { puts "captured" }

arr = %w[apple banana cherry]
up = arr.map(&:upcase)   # symbol to proc
puts up.inspect

Explanation

Blocks are nameless chunks of code implicitly passed to methods and invoked with yield. Procs and lambdas wrap blocks as first-class objects with different return and arity rules: lambdas check argument count strictly and return only from themselves. The & operator converts between blocks and Procs, and Symbol#to_proc enables the concise &:upcase idiom.

More Ruby Snippets