Lambdas let you create small pieces of reusable code that you can run later. They help keep your code neat and organized.
Lambda creation and behavior in 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.
greet = ->(name) { puts "Hello, #{name}!" }
greet.call("Alice")square = lambda { |x| x * x } puts square.call(4)
adder = ->(a, b) { a + b }
result = adder.call(3, 5)
puts resultThis 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.
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()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.
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.