TExcelTAD
Home › Ruby › Ruby Procs & Lambdas

Ruby Procs & Lambdas

A block is not an object — it only exists attached to a method call. When you want to store a piece of code in a variable, pass it around, or keep it for later, you turn it into a Proc object. Ruby has two flavours: procs and lambdas.

Creating and calling them

ruby · try it yourself
square = lambda { |x| x * x }
cube = ->(x) { x * x * x }          # "stabby lambda" syntax
shout = proc { |s| s.upcase + "!" }
hello = Proc.new { |name| "Hello #{name}" }

p square.call(4)
p cube.(3)
p shout["hey"]
p hello.call("Ivy")
p square.class, cube.lambda?, shout.lambda?
16
27
"HEY!"
"Hello Ivy"
Proc
true
false

All four are Proc objects. You can call them with .call(...), .(...) or [...].

Storing behaviour in data

Because procs are objects, you can put them in arrays and hashes:

ruby · try it yourself
operations = {
  "+" => ->(a, b) { a + b },
  "-" => ->(a, b) { a - b },
  "*" => ->(a, b) { a * b },
  "/" => ->(a, b) { b.zero? ? "cannot divide by zero" : a.fdiv(b) },
}

[["+", 7, 3], ["*", 6, 7], ["/", 1, 0], ["/", 9, 4]].each do |op, a, b|
  puts "#{a} #{op} #{b} = #{operations[op].call(a, b)}"
end
7 + 3 = 10
6 * 7 = 42
1 / 0 = cannot divide by zero
9 / 4 = 2.25

Passing a proc as a block with &

The & operator converts a proc into a block when calling a method:

ruby · try it yourself
double = ->(n) { n * 2 }
is_big = ->(n) { n > 5 }

p [1, 4, 7].map(&double)
p [1, 4, 7].select(&is_big)
p %w[a b].map(&:upcase)   # a symbol works too: Symbol#to_proc
[2, 8, 14]
[7]
["A", "B"]

Lambda vs proc: two differences

1. Arguments. A lambda is strict about the number of arguments, like a method. A proc is relaxed: missing arguments become nil, extra ones are ignored.

ruby · try it yourself
strict = ->(a, b) { "#{a}-#{b}" }
loose = proc { |a, b| "#{a.inspect}-#{b.inspect}" }

p loose.call(1)
p loose.call(1, 2, 3)

begin
  strict.call(1)
rescue ArgumentError => e
  puts "lambda: #{e.message}"
end
"1-nil"
"1-2"
lambda: wrong number of arguments (given 1, expected 2)

2. return. Inside a lambda, return leaves just the lambda. Inside a proc, return leaves the method the proc was defined in:

ruby · try it yourself
def using_lambda
  check = -> { return "from lambda" }
  check.call
  "method finished"
end

def using_proc
  check = proc { return "from proc" }
  check.call
  "method finished"
end

p using_lambda
p using_proc
"method finished"
"from proc"
Lambda Proc
Create with ->(x) { }, lambda { } proc { }, Proc.new { }
Wrong argument count ArgumentError missing → nil, extras ignored
return exits the lambda only exits the enclosing method
Behaves like a method a block

Tip: When in doubt, use a lambda. Its behaviour is the least surprising.

Closures remember their surroundings

A proc or lambda keeps access to the variables that existed where it was created — even after that method has finished:

ruby · try it yourself
def make_counter
  count = 0
  increment = -> { count += 1 }
  current = -> { count }
  [increment, current]
end

inc, get = make_counter
inc.call
inc.call
inc.call
p get.call

def multiplier(factor)
  ->(n) { n * factor }
end

triple = multiplier(3)
p triple.call(14)
p [1, 2, 3].map(&multiplier(10))
3
42
[10, 20, 30]

Composition and currying

Lambdas can be combined with >> and <<, and partially applied with curry:

ruby · try it yourself
add_tax = ->(price) { price * 1.2 }
round2 = ->(x) { x.round(2) }
format = ->(x) { "EUR #{x}" }

pipeline = add_tax >> round2 >> format
p pipeline.call(9.99)

volume = ->(l, w, h) { l * w * h }
box_of_depth_two = volume.curry[2]
p box_of_depth_two[3][4]
"EUR 11.99"
24

f >> g means "first f, then g".

Methods as objects

You can also grab an existing method as an object with method(:name):

ruby · try it yourself
def celsius_to_f(c) = c * 9.0 / 5 + 32

converter = method(:celsius_to_f)
p converter.call(100)
p [0, 37, -40].map(&converter)
p converter.arity
212.0
[32.0, 98.6, -40.0]
1

arity tells how many arguments a callable expects.

Test yourself

What happens when a lambda expecting 2 arguments is called with 1?

  1. The missing one becomes nil
  2. ArgumentError is raised
  3. It returns nil
  4. It waits for the second argument

Which syntax creates a lambda?

  1. proc { |x| x }
  2. Proc.new { |x| x }
  3. ->(x) { x }
  4. block { |x| x }

In [1, 2].map(&doubler), what does & do?

  1. Takes a reference
  2. Converts the proc into the method's block
  3. Performs a bitwise AND
  4. Copies the array