Lambda
A lambda is a careful kind of Proc that checks how many inputs you gave it, like a strict form that must be completely filled. It is written with the arrow shortcut or the word lambda.
In this page:
Syntax
lambda_name = lambda { |param| expression }
lambda_name = ->(param) { expression }
lambda_name.call(argument)
Lambda
A lambda (created with lambda { ... } or the -> "stabby lambda" syntax) is similar to a Proc but behaves more like a regular method: it enforces the exact number of arguments, and return inside it only exits the lambda itself, not the enclosing method.
Lambdas are generally preferred over Procs when you want method-like strictness and behavior. Both Proc and Lambda are instances of the same Proc class under the hood.
Note:
The
->(x) { x * x } stabby lambda syntax is the more modern, concise way to write a lambda compared to lambda { |x| x * x }.Example: Lambda
square = lambda { |x| x * x }
cube = ->(x) { x * x * x }
puts square.call(4)
puts cube.call(3)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
lambdaand calling with the wrong number of arguments, which raisesArgumentError. - Writing
lambda { |x| x * x }and calling it assquare(4), which raisesNoMethodError; a lambda must be called withsquare.call(4),square.(4)orsquare[4]. - Forgetting
.calland printing the lambda object instead of its result.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: