Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 21 of 23 · Ruby 4.0

Store behavior with procs and lambdas

Save a block as a callable object and pass behavior to a method.

Learn

A block can become a Proc object that you store in a variable and invoke with call. proc { |value| value * 2 } creates one; ->(value) { value * 2 } creates a lambda, which is also a Proc. Both can use local variables from the surrounding scope where they were created.

A method can accept a callable as an ordinary argument and invoke it with call. A lambda checks arguments like a method, while an ordinary proc handles missing or extra arguments more permissively. return inside a lambda returns from that lambda; return inside an ordinary proc tries to return from the enclosing method where the proc was created. Prefer a lambda when you want method-like argument and return behavior.

Example

double = proc { |value| value * 2 }
triple = ->(value) { value * 3 }
p double.call(4)
p triple.call(4)

Experiment

  • Predict the two results. Add a new lambda as a pricing rule without changing quote.

  • Predict both calls. Change fee before the second call and check whether the proc uses the updated local variable.

  • Predict what each call does. Supply a value to each callable and compare with calling without arguments.

Explore the official manual

Ruby 4.0.0 · Example

Ready to run

Output

Run the code to see what happens.