Skip to content
Ruby

Blocks, Procs, Lambdas

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

#block#proc#lambda

Code

ruby
# 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