typestar

Procs and lambdas in Ruby

Blocks captured as objects you can store, pass and compose.

double = ->(n) { n * 2 }
puts double.call(21)
puts double.(5)

add = lambda { |a, b| a + b }
puts add.call(2, 3)

shout = proc { |w| w.to_s.upcase }
puts shout.call("hey")

# procs are objects: store them, pass them, chain them
steps = [double, ->(n) { n + 1 }]
puts steps.reduce(10) { |acc, fn| fn.call(acc) }

How it works

  1. -> builds a lambda; .call and .() both invoke it.
  2. lambda and proc differ in arity checking and return.
  3. A list of callables folds over a value one step at a time.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
310
Tokens
106
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 3 of 3 in Methods & blocks, step 18 of 29 in Language basics.

← Previous Next →