← Back to the PhRUG counter demo

What is a lambda?

A lambda is code you can save in a variable and run later. In Ruby, it is a kind of Proc object. Ruby 4.0 Proc documentation

Create and call a lambda

double = ->(number) { number * 2 }
p double.call(4)  # 8

The arrow creates the lambda. (number) names its input, and the braces hold the code to run. double.call(4) runs that code with number set to 4. Ruby 4.0 lambda syntax

Why the counter remembers

def make_counter
  count = 0
  -> { count += 1 }
end

first = make_counter
second = make_counter
p first.call   # 1
p first.call   # 2
p second.call  # 1

make_counter returns a lambda that can still read and update count after the method finishes. The lambda and its access to that variable form a closure. Each call to make_counter creates a separate count, so second.call starts from zero even after two calls to first. Ruby 4.0 Proc documentation