Skip to content
Procs and Lambdas
step 1/6

Reading — step 1 of 6

Learn

~1 min readBlocks, Procs, Lambdas

Blocks aren't first-class — you can't store one in a variable directly. Procs and lambdas are blocks-as-objects.

Proc:

square = Proc.new { |n| n * n }
square.call(5)        # 25
square.(5)            # 25 — same
square[5]             # 25 — also same

Lambda: (preferred for most uses)

square = ->(n) { n * n }                 # arrow syntax
square = lambda { |n| n * n }            # explicit syntax
square.call(5)        # 25

Differences (lambda is stricter):

  • Lambdas check arity (->(a, b) {}.call(1) errors). Procs don't (extras dropped, missing args become nil).
  • return in a lambda returns from the lambda. return in a proc returns from the enclosing method — gotcha.

Converting between blocks and procs:

# Block to proc inside a method definition
def wrap(&blk)            # &blk captures the block as a Proc
  blk.call("hello")
end
wrap { |s| puts s.upcase }

# Proc to block when calling
square = ->(n) { n * n }
[1, 2, 3].map(&square)    # [1, 4, 9]

The & either converts a block param to a Proc or splats a Proc as a block — same operator, two directions.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…