Lambda (Ruby)

A lambda is a Proc-like object that checks its argument count strictly and returns only from itself. Written with ->(x) { ... } or lambda { ... }, it behaves more like a normal method than a plain Proc.

Ruby

A lambda is a special kind of Proc. The two key differences: a lambda enforces arity (passing the wrong number of arguments raises an error, whereas a Proc tolerates it), and return inside a lambda returns from the lambda only, not from the surrounding method.

The 'stabby' syntax ->(args) { body } is the modern form; you call it with my_lambda.call(args), my_lambda.(args), or my_lambda[args]. Because its return semantics are method-like, a lambda is usually the safer choice when you want a self-contained function value.

Use a lambda when you want strict, predictable behavior (validation callbacks, function arguments), and a plain Proc when you specifically want lenient arguments or non-local return. Both are objects you can store and pass.

Syntax

add = ->(a, b) { a + b }
add.call(2, 3)

Examples

Ruby

square = ->(x) { x * x }
puts square.call(6)
puts square.(7)
puts square.lambda?

Output:

36
49
true

Learn it in a lesson

See also

Back to the Dictionary