AnyCompiler

Blocks, Procs, and Lambdas

A block is a chunk of code attached directly to a method call — either { |params| ... } or the equivalent do |params| ... end. It isn't a value; it isn't assigned to a variable or passed as a normal argument. A method receives the block that was attached to its call and runs it with yield, which is a keyword, not a method.

3.times { |i| puts "block: #{i}" }

def repeat(n)
  n.times { |i| yield i }
end

repeat(3) { |i| puts "yielded: #{i}" }
Output
block: 0
block: 1
block: 2
yielded: 0
yielded: 1
yielded: 2

repeat(3) { |i| ... } attaches a block to the call; inside repeat, yield i hands control to that attached block, passing it i. This is Ruby's own mechanism — not a lambda literal the way JavaScript's (x) => x or Python's lambda x: x assign an anonymous function to a value. There is a way to turn a block into an actual object, though: Proc.new captures a block as a value, and -> (the "stabby lambda") is a lambda literal built the same way.

square = ->(x) { x * x }
cube = lambda { |x| x ** 3 }
adder = Proc.new { |x, y| x + y }

puts square.call(4)
puts cube.(3)
puts adder[2, 5]
Output
16
27
7

.call, .(), and [] are three interchangeable ways to invoke a Proc or lambda — once a block is captured as an object this way, it behaves like any other value: it can be stored in a variable, passed as a normal argument, and invoked whenever you like. Next: Enumerable methods — map, select, and reduce, chained together, building directly on blocks.

Practice exercise

Write def repeat(n) that yields each index from 0 to n-1 to its block. Call repeat(5) with a block that adds each i to a total, then print total.