Kernel#lambda
lambda { |params| block } -> proc Returns:
Proc · Added in v1.8.7 · Updated March 13, 2026 · Kernel Methods lambda proc closure blocks functional
lambda is a Kernel method that creates an anonymous function (a Proc object) that behaves like a closure. Unlike plain blocks, lambdas are objects that can be stored in variables, passed to methods, and returned from methods. They enforce strict argument checking compared to procs.
Syntax
lambda { |params| block }
lambda do |params|
# block body
end
->(params) { block } #stabby lambda syntax (Ruby 1.9+)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
block | block | required | The code to execute when the lambda is called |
Examples
Basic Usage
square = lambda { |x| x ** 2 }
square.call(5)
# => 25
# Or using .()
square.(5)
# => 25
Stabby Lambda Syntax
cube = ->(x) { x ** 3 }
cube.call(3)
# => 27
# Multiple parameters
add = ->(a, b) { a + b }
add.call(10, 5)
# => 15
Passing Lambdas to Methods
def apply_operation(num, operation)
operation.call(num)
end
double = ->(x) { x * 2 }
apply_operation(10, double)
# => 20
Lambda vs Proc: Argument Checking
The key difference between lambdas and procs is argument handling:
# Lambda: strict argument checking
square = lambda { |x| x ** 2 }
square.call(5, 10)
# => ArgumentError: wrong number of arguments (given 2, expected 1)
# Proc: loose argument checking
my_proc = proc { |x, y| [x, y] }
my_proc.call(5, 10)
# => [5, 10]
my_proc.call(5)
# => [5, nil]
Return Behavior
Lambdas return like methods, procs return like blocks:
def test_lambda
l = lambda { return 100 }
l.call
"after lambda" # This executes
end
def test_proc
p = proc { return 200 }
p.call
"after proc" # This does NOT execute - method returns 200
end
test_lambda # => "after lambda"
test_proc # => 200
Common Patterns
Using Lambdas as Callback Functions
class EventHandler
def initialize
@handlers = {}
end
def on(event, &callback)
@handlers[event] = callback
end
def trigger(event, *args)
@handlers[event]&.call(*args)
end
end
handler = EventHandler.new
handler.on(:click) { |data| puts "Clicked: #{data}" }
handler.trigger(:click, "button")
# Clicked: button
Currying
add = ->(a, b) { a + b }
add_five = add.curry[5]
add_five(10)
# => 15
Composition
square = ->(x) { x ** 2 }
double = ->(x) { x * 2 }
composed = ->(x) { square.call(double.call(x)) }
composed.call(5)
# => 100 (5*2 = 10, 10**2 = 100)