๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Lambdas

A lambda is a strict kind of stored block. It checks how many values it receives before it runs.

A lambda built with ->

triple is a lambda that multiplies its value by three. call runs it with 4.

triple = ->(n) { n * 3 }
puts triple.call(4)

A proc fills a missing value with nil

pair is a plain proc that expects two values. It receives one, so the second value becomes nil and prints as an empty line.

pair = Proc.new do |a, b|
  puts a
  puts b
end
pair.call("only")

A lambda with the wrong count fails

add is a lambda that expects two values. It receives one value, so the program fails before anything prints.

add = lambda do |a, b|
  a + b
end
puts add.call(5)

return leaves only the lambda

pick is a lambda that returns the word early. The word after return never runs, and the method keeps going.

def check
  pick = lambda do
    return "early"
  end
  word = pick.call
  puts word
  puts "method continues"
end
check

Example

greet = lambda do |name|
  "Hello, #{name}"
end
puts greet.call("Ana")
puts greet.call("Ben")

Key points

  • The word lambda builds a lambda from a block.
  • The -> shape builds a lambda too, with its parameters in parentheses.
  • A lambda raises an error when it receives the wrong number of values.
  • A plain proc fills a missing value with nil instead of raising.
  • return inside a lambda leaves only the lambda.

In this example, greet is a lambda that builds a greeting from one name. call runs it twice with two different names. Each greeting prints on its own line.

Note

Lambdas and procs both run with call.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when a lambda receives too few values?