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
->builds a lambda;.calland.()both invoke it.lambdaandprocdiffer in arity checking and return.- A list of callables folds over a value one step at a time.
Keywords and builtins used here
lambdaprocputs
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.
Step 3 of 3 in Methods & blocks, step 18 of 29 in Language basics.