0
0
RubyHow-ToBeginner · 3 min read

How to Use Stabby Lambda in Ruby: Syntax and Examples

In Ruby, a stabby lambda is created using the -> symbol followed by parameters in parentheses and a block. For example, ->(x) { x * 2 } defines a lambda that doubles its input.
📐

Syntax

The stabby lambda uses the -> symbol to define an anonymous function. You write parameters inside parentheses immediately after ->, then provide the block of code inside curly braces or do...end.

  • ->(params): Defines the lambda and its parameters.
  • Block: The code inside { } or do...end that runs when the lambda is called.
ruby
double = ->(x) { x * 2 }
💻

Example

This example shows how to create a stabby lambda that adds two numbers and then call it with arguments.

ruby
add = ->(a, b) { a + b }
result = add.call(3, 5)
puts result
Output
8
⚠️

Common Pitfalls

One common mistake is confusing lambdas with procs, especially in how they handle return and argument checking. Lambdas check the number of arguments strictly and treat return differently than procs.

Also, forgetting to use .call to execute the lambda will not run the code.

ruby
wrong = ->(x) { return x * 2 }
# Using return inside lambda is fine, but calling without .call won't run it

# Correct usage:
correct = ->(x) { x * 2 }
puts correct.call(4)  # Outputs 8
Output
8
📊

Quick Reference

  • Define: lambda = ->(params) { code }
  • Call: lambda.call(args)
  • Strict argument checking: Lambdas require exact number of arguments.
  • Return behavior: return exits only the lambda, not the enclosing method.

Key Takeaways

Use ->(params) { code } to define a stabby lambda in Ruby.
Call the lambda with .call(args) to execute its code.
Lambdas check arguments strictly and handle return differently than procs.
Forgetting .call means the lambda code won't run.
Stabby lambdas are a concise way to write anonymous functions in Ruby.