0
0
RubyConceptBeginner · 3 min read

What is Lambda in Ruby: Simple Explanation and Examples

In Ruby, a lambda is a special kind of anonymous function that you can store in a variable and call later. It behaves like a method with strict argument checking and returns control to the calling code when it finishes.
⚙️

How It Works

A lambda in Ruby is like a small, reusable recipe that you can carry around and use whenever you want. Imagine you have a recipe card that tells you how to make a sandwich. You can keep this card in your pocket and use it anytime you want to make that sandwich. Similarly, a lambda holds a block of code that you can save in a variable and run later.

When you call a lambda, it runs the code inside it just like a method. But unlike some other blocks of code in Ruby, a lambda checks if you give it the right number of ingredients (arguments). If you don’t, it will raise an error. Also, when a lambda finishes running, it returns control back to the place where it was called, not exiting the whole method or program.

đź’»

Example

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

ruby
add = ->(a, b) { a + b }
result = add.call(3, 4)
puts result
Output
7
🎯

When to Use

Use a lambda when you want to pass around a small piece of code that behaves like a method. It is useful when you want to reuse logic without writing a full method or when you want to pass a block of code as an argument to another method.

For example, you might use a lambda to define a custom sorting rule, to filter data, or to delay some calculation until later. Lambdas are great when you need strict argument checking and want the code to return control normally after running.

âś…

Key Points

  • A lambda is an anonymous function stored in a variable.
  • It checks the number of arguments strictly.
  • Returns control to the caller after execution.
  • Useful for passing reusable code blocks.
âś…

Key Takeaways

A lambda is a reusable anonymous function with strict argument rules.
It returns control normally to the calling code after running.
Use lambdas to pass small pieces of code as variables or arguments.
Lambdas help keep your code clean and flexible.