How to Create Lambda in Ruby: Syntax and Examples
In Ruby, you create a lambda using the
lambda keyword or the shorthand -> syntax. A lambda is an anonymous function that you can store in a variable and call later with .call.Syntax
You can create a lambda in Ruby using two main ways:
lambda { |args| ... }- uses thelambdakeyword with a block.->(args) { ... }- uses the arrow shorthand syntax.
Both create a lambda object that you can call with .call.
ruby
my_lambda = lambda { |x| x * 2 }
my_lambda_shorthand = ->(x) { x * 2 }Example
This example shows how to create a lambda that doubles a number and then call it.
ruby
double = ->(n) { n * 2 }
puts double.call(5)Output
10
Common Pitfalls
One common mistake is confusing lambdas with procs. Lambdas check the number of arguments strictly, while procs do not. Also, forgetting to use .call to execute the lambda will not run the code.
Wrong: my_lambda(5) (raises error)
Right: my_lambda.call(5)
ruby
my_lambda = ->(x) { x + 1 }
# Wrong usage:
# my_lambda(5) # This will cause an error
# Correct usage:
puts my_lambda.call(5) # Outputs 6Output
6
Quick Reference
| Syntax | Description |
|---|---|
| lambda { |args| ... } | Create a lambda using the lambda keyword |
| ->(args) { ... } | Create a lambda using arrow shorthand |
| .call(args) | Invoke the lambda with arguments |
| Proc.new { |args| ... } | Create a proc (different from lambda) |
Key Takeaways
Create lambdas in Ruby using either lambda { |args| ... } or ->(args) { ... } syntax.
Always use .call to execute a lambda; calling it like a method without .call causes errors.
Lambdas strictly check the number of arguments passed, unlike procs.
Lambdas are useful for storing blocks of code that can be reused and passed around.
Use the arrow syntax -> for shorter, cleaner lambda expressions.