Skip to main content
Back to Journal
Ruby

Lambdas vs Procs vs Blocks

Blocks, Procs, and Lambdas in Ruby

Ruby provides three ways to group code into callable units: blocks, procs, and lambdas. Understanding the differences between them is essential for writing idiomatic Ruby.

Blocks

Blocks are chunks of code enclosed between do...end or curly braces. They can be passed to methods and executed with yield:

[1, 2, 3].each do |num|
  puts num
end

[1, 2, 3].each { |num| puts num }

Procs

A Proc is an object that encapsulates a block of code. Unlike blocks, procs are objects and can be stored in variables:

my_proc = Proc.new { |x| puts x * 2 }
my_proc.call(5) # outputs 10

# Procs don't check argument count
my_proc.call(5, 6) # still works, ignores extra args

Lambdas

Lambdas are similar to procs but with two key differences:

my_lambda = lambda { |x| puts x * 2 }
# Or using the stabby lambda syntax
my_lambda = ->(x) { puts x * 2 }

# Lambdas DO check argument count
my_lambda.call(5)    # works
my_lambda.call(5, 6) # ArgumentError!

Key Differences

  1. Argument checking: Lambdas check the number of arguments; procs do not.
  2. Return behavior: A return inside a lambda returns from the lambda itself. A return inside a proc returns from the enclosing method.

When to Use What

Use blocks for simple iterations and callbacks. Use procs when you need to store a block as an object. Use lambdas when you want strict argument checking and predictable return behavior.

RubyBlocksProcsLambdas