0
0
Rubyprogramming~5 mins

Lambda creation and behavior in Ruby

Choose your learning style9 modes available
Introduction

Lambdas let you create small pieces of reusable code that you can run later. They help keep your code neat and organized.

When you want to pass a small function as an argument to another method.
When you need a block of code that you can store and call multiple times.
When you want to create a quick function without naming it.
When you want to control how arguments are checked and how returns behave in a block of code.
Syntax
Ruby
my_lambda = ->(parameters) { code }
# or
my_lambda = lambda { |parameters| code }

The arrow syntax -> is a short way to create a lambda.

Lambdas check the number of arguments strictly and return control to the calling method when they finish.

Examples
This creates a lambda that says hello to a name and then calls it with "Alice".
Ruby
greet = ->(name) { puts "Hello, #{name}!" }
greet.call("Alice")
This lambda calculates the square of a number and prints 16.
Ruby
square = lambda { |x| x * x }
puts square.call(4)
This lambda adds two numbers and prints the result 8.
Ruby
adder = ->(a, b) { a + b }
result = adder.call(3, 5)
puts result
Sample Program

This program creates a lambda that greets a person by name. It shows how calling it without arguments causes an error because lambdas check arguments strictly. It also shows how a return inside a lambda only exits the lambda, not the whole method.

Ruby
say_hello = ->(name) { "Hello, #{name}!" }

puts say_hello.call("Bob")

# Showing argument check
begin
  say_hello.call
rescue ArgumentError => e
  puts "Error: #{e.message}"
end

# Showing return behavior
def test_lambda
  l = -> { return "Returned from lambda" }
  result = l.call
  return "Returned from method after lambda: #{result}"
end

puts test_lambda()
OutputSuccess
Important Notes

Lambdas are like methods inside variables.

They check the number of arguments strictly, unlike regular blocks.

Return inside a lambda exits only the lambda, not the surrounding method.

Summary

Lambdas are small, reusable pieces of code you can store in variables.

They check arguments strictly and have special return behavior.

You create them using -> or lambda keywords.