Thuta Learning
Ruby
AdvancedProgrammingBeginner

Procs, Lambdas & Closures

RubyLesson 2535 min

What you'll walk away with

  • Create a Proc and a lambda and tell them apart with lambda?
  • Predict what each one does when it receives too few or too many arguments
  • Explain how return behaves inside a lambda and inside a proc
  • Write closures such as counters, and convert between blocks, Procs, method(:name) and &:symbol

Explain it simply

Explain it simply

A block is a chunk of code you hand to a method, like a sticky note attached to a single call: items.each { |item| puts item }. The note belongs to that one call and is gone afterwards. A Proc turns the same chunk of code into an object, so you can keep it in a variable, pass it around and run it whenever you like, as many times as you like.

A lambda is a Proc with stricter manners. It insists on the right number of arguments, and a return inside it leaves only the lambda, just as a return inside a method leaves that method. Both remember the local variables that existed when they were created, which is why they are called closures.

Problem → Why → Solution

The problem: a block cannot be saved under a name

Say you want to use one pricing rule in two places. With blocks alone you must copy and paste the code, and as soon as you fix one copy and forget the other, you have two different rules. You would like to put the rule in a variable, but a block is not a value, so you cannot write that: Ruby reads the { as the start of a hash literal and reports a syntax error.

Once you do use Procs, two more surprises wait. A return inside a proc does not leave the proc but the method the proc was written in, and if you call the proc after that method has finished you get a LocalJumpError. The code below shows all three problems.

problem.rb
prices  = [10, 25, 40]
refunds = [5, 12]

# The same rule pasted twice: easy to fix in one place and forget in the other
with_tax   = prices.map  { |amount| (amount * 1.2).round(2) }
refund_tax = refunds.map { |amount| (amount * 1.2).round(2) }

# A block cannot be saved in a variable
add_tax = { |amount| (amount * 1.2).round(2) }   # SyntaxError: { starts a hash literal

# A proc that outlives its method cannot return from it
def build_checker
  proc { |n| return n > 0 }
end
build_checker.call(5)                            # LocalJumpError: unexpected return

Why does this happen?

A block is part of a method call, not an object of its own. So Ruby has the Proc class for holding code as a value. There are two kinds of Proc, proc and lambda, because sometimes you want the loose, block-like behaviour and sometimes the strict, method-like behaviour.

Core concept: Procs, lambdas and closures

Every callable you can store in Ruby is an instance of the Proc class. There are four ways to make one: proc { |x| ... } and Proc.new { |x| ... } give you a plain proc, while lambda { |x| ... } and the stabby literal ->(x) { ... } give you a lambda. The only difference between the two kinds is a hidden flag that proc.lambda? reports, and that flag changes two behaviours: how arguments are checked and what return means. You run either kind with call, with the shorter .() or with square brackets, so double.call(4), double.(4) and double[4] are the same thing.

Arguments first. A lambda is as strict as a method: calling a two-parameter lambda with one argument raises ArgumentError. A plain proc is forgiving. A missing argument becomes nil, extra ones are silently dropped, and a single array is spread across the parameters, which is why [[1, 2], [3, 4]].map { |a, b| a + b } works. That forgiveness is handy for blocks, but it can hide a typo for a long time, so a callable you store and reuse is usually better written as a lambda.

Now return. Inside a lambda, return leaves the lambda and hands a value back to whoever called it. Inside a proc, return does not belong to the proc at all: it returns from the method in which the proc was written. If that method has already finished, Ruby raises LocalJumpError because there is nothing left to return from. When you only want to finish the current block early, use next, which behaves the same way in both kinds.

text
Where return goes
-----------------
run_lambda                           run_proc
  |                                    |
  +-- checker = -> { return :a }       +-- checker = proc { return :b }
  +-- checker.call                     +-- checker.call
  |      return leaves only the        |      return leaves run_proc too
  |      lambda                        |
  +-- :after_lambda   (reached)        +-- :after_proc     (skipped)

Finally, closures. A Proc carries its surroundings with it: the local variables that were visible where it was created stay reachable even after the method that created them has returned. The Proc holds the variable itself, not a copy of its value at that moment, so if the variable changes later the proc sees the new value. That is how you build a counter, or a discount rule that remembers its settings.

Behaviourproclambda
Created withproc { }, Proc.new { }lambda { }, ->() { }
Wrong argument countFills nil, drops extrasRaises ArgumentError
returnLeaves the enclosing methodLeaves only the lambda
lambda?falsetrue
Mental model: code saved as an object
  1. A block is code glued to one call
  2. A Proc saves that code as an object
  3. A lambda checks args like a method
  4. Both remember surrounding variables

If you remember one rule: a lambda behaves like a method, a proc behaves like a block.

General pattern

ruby
callable = ->(param) { expression }         # lambda, stabby literal
callable = lambda { |param| expression }    # lambda, older spelling
callable = proc { |param| expression }      # proc

callable.call(arg)      # same as callable.(arg) and callable[arg]
callable.lambda?        # true for a lambda, false for a proc

some_method(&callable)  # pass it where a block is expected

A callable is built in one of three ways and then run with call, .() or []. When a method expects a block, put & in front of the callable to pass it.

Example: comparing a pricing lambda with procs

This single file shows all four rules from above. The add_tax lambda holds tax_rate as a closure. The lenient proc and the strict lambda share one body, so you can see how each reacts to the wrong number of arguments. The last two methods show the difference in return. Try to predict every printed line before you run it.

callables.rb
tax_rate = 0.2

add_tax = ->(price) { (price * (1 + tax_rate)).round(2) }
lenient = proc { |a, b| "a=#{a.inspect}, b=#{b.inspect}" }
strict  = lambda { |a, b| "a=#{a.inspect}, b=#{b.inspect}" }

# 1. Three ways to call, plus the lambda? flag
puts add_tax.call(50)
puts add_tax.(10)
puts add_tax[19.99]
puts "add_tax lambda? #{add_tax.lambda?}"
puts "lenient lambda? #{lenient.lambda?}"

# 2. Arguments: the proc forgives, the lambda objects
puts lenient.call(1)
puts lenient.call(1, 2, 3)
puts lenient.call([7, 8])
begin
  strict.call(1)
rescue ArgumentError => e
  puts "lambda raised: #{e.message}"
end

# 3. Closure: the lambda sees the new value of tax_rate
tax_rate = 0.25
puts add_tax.call(50)

# 4. return: a lambda leaves itself, a proc leaves its method
def run_lambda
  checker = -> { return :from_lambda }
  checker.call
  :after_lambda
end

def run_proc
  checker = proc { return :from_proc }
  checker.call
  :after_proc
end

p run_lambda
p run_proc

Code breakdown

  1. Lambda + closureadd_tax = ->(price) { (price * (1 + tax_rate)).round(2) }

    Builds a stabby lambda. tax_rate is a variable from outside the lambda, and the lambda holds on to it, which is what makes it a closure. add_tax.call(50) computes 50 * 1.2 = 60.0.

  2. Call formsputs add_tax.(10)

    .() is shorthand for call, and add_tax[19.99] does the same. 19.99 * 1.2 is 23.988, which round(2) turns into 23.99.

  3. Lenient procputs lenient.call(1, 2, 3)

    The proc takes two parameters and quietly drops the extra 3, so a=1, b=2 is printed. lenient.call(1) leaves b as nil, and lenient.call([7, 8]) spreads the array across a and b.

  4. Strict lambdastrict.call(1)

    This lambda has the same body but refuses to run with only one argument. The ArgumentError message is the same one a method would give: "wrong number of arguments (given 1, expected 2)".

  5. Closure sees changestax_rate = 0.25

    tax_rate changes after the lambda was built. add_tax.call(50) now returns 62.5, because the lambda holds the variable, not a copy of its old value.

  6. return in each kindchecker = proc { return :from_proc }

    The return in run_proc's proc also leaves run_proc, so :after_proc is never reached and :from_proc comes back. In run_lambda only the lambda is left, and :after_lambda is returned.

You should see
60.0
12.0
23.99
add_tax lambda? true
lenient lambda? false
a=1, b=nil
a=1, b=2
a=7, b=8
lambda raised: wrong number of arguments (given 1, expected 2)
62.5
:after_lambda
:from_proc

Closures as private state

Local variables normally disappear when a method ends, but a closure that holds one keeps it alive. Every call to make_counter below creates a fresh count variable and returns two lambdas that both see that same variable. A second counter has its own count and does not disturb the first. Getting private state without writing a class is the strength of closures.

counter.rb
def make_counter
  count = 0
  increment = -> { count += 1 }
  read = -> { count }
  [increment, read]
end

increment, read = make_counter
increment.call
increment.call
puts read.call            # 2

_other_increment, other_read = make_counter
puts other_read.call      # 0, a separate count

From blocks to Procs, symbols and methods

A trailing &name in a method's parameter list catches the block that was passed in as a Proc object. In the other direction, writing &callable at the call site passes a Proc back as a block. With &:upcase, Ruby uses Symbol#to_proc to turn the symbol into a Proc, and method(:shout) wraps an existing method as a Method object. These conversions are shorter than a plain block and let you reuse a named method.

conversions.rb
def shout(text) = text.upcase + "!"

def apply_to_all(items, &transform)
  items.map(&transform)
end

words = %w[ruby gems minitest]

p apply_to_all(words) { |word| word.capitalize }  # ["Ruby", "Gems", "Minitest"]
p apply_to_all(words, &:upcase)                   # ["RUBY", "GEMS", "MINITEST"]
p apply_to_all(words, &method(:shout))            # ["RUBY!", "GEMS!", "MINITEST!"]

shouter = method(:shout)
puts shouter.class                # Method
puts shouter.to_proc.lambda?      # true
puts :upcase.to_proc.call("abc")  # ABC

curry and composition

Calling curry on a lambda gives you a lambda that accepts its arguments one at a time. You can supply some arguments now and the rest later, so discount.curry[10] becomes a ready-made "ten percent off" rule. >> and << chain two callables: f >> g runs f first and g second, while f << g runs g first.

curry.rb
discount = ->(percent, price) { price - price * percent / 100.0 }

ten_off = discount.curry[10]
puts ten_off.call(200)            # 180.0
puts ten_off.(80)                 # 72.0
puts discount.curry.(25).(40)     # 30.0
puts discount.curry.(25, 40)      # 30.0

double = ->(n) { n * 2 }
increment = ->(n) { n + 1 }
double_then_increment = double >> increment
increment_then_double = double << increment
puts double_then_increment.call(5)   # 11
puts increment_then_double.call(5)   # 12

In real projects

Where this shows up in real projects

You meet Procs and lambdas daily in Ruby code, even when you never type the words. Every &:name you pass to map turns a Symbol into a Proc. Rails scopes are lambdas, for example scope :published, -> { where(published: true) }, because the condition must be evaluated each time it is used, not once when the class loads. A Rack application is anything that responds to call(env), so a lambda returning a status, headers and a body is a complete web app. Hash.new { |hash, key| hash[key] = [] } stores a block that computes a default whenever a key is missing.

Closures are also how libraries let you plug in behaviour. A test framework such as RSpec or Minitest spec stores each test body as a block and runs it later, a Rake task keeps your block until you ask for it, and a callback such as before_action remembers the block or method name you gave it. When you design your own code, accept a block for one-off behaviour, and accept a lambda (or any object with call) when the behaviour needs a name, has to live in a list or has to be chosen at runtime, such as a set of pricing rules or validators.

Common mistakes

Common mistakes

1. Using return in a proc that outlives its method

build_checker returns proc { |n| return n > 0 }. Calling it later raises LocalJumpError: unexpected return, because the method that owns the return has already finished. If the callable needs its own return, use a lambda, and inside a block use next to leave early.

2. Trusting a proc to check its arguments

A proc does not complain about wrong arguments. A missing one becomes nil and surfaces later as an unrelated NoMethodError. Write any callable you store in a variable and call from several places as a lambda.

3. Passing a lambda where the array would be spread

pairs.map(&->(a, b) { a + b }) raises ArgumentError (given 1, expected 2), while a block or a proc works. A lambda converted with & stays strict. Take a single parameter, or destructure inside parentheses with ->((a, b)).

4. Closures sharing one variable in a for loop

A for loop does not create a new variable on each pass, so every lambda inside it sees the final value and you get [3, 3, 3]. The block parameter of each, map and times is new on every pass, so use those.

mistakes.rb
pairs = [[1, 2], [3, 4]]
p pairs.map { |a, b| a + b }                 # [3, 7]
p pairs.map(&proc { |a, b| a + b })          # [3, 7]
begin
  pairs.map(&->(a, b) { a + b })
rescue ArgumentError => e
  puts "lambda: #{e.message}"                # ... (given 1, expected 2)
end
p pairs.map(&->((a, b)) { a + b })           # [3, 7]

callbacks = []
for number in 1..3
  callbacks << -> { number }
end
p callbacks.map(&:call)                      # [3, 3, 3]

callbacks = (1..3).map { |number| -> { number } }
p callbacks.map(&:call)                      # [1, 2, 3]

Best practices

Best practices

  • Write any callable you store in a variable or a list as a lambda, and keep plain blocks for one-off behaviour in a single method call.
  • Use next, not return, to leave a block early.
  • Use &:name when you only call one method; write bigger logic as an ordinary named method and pass it with method(:name) so you can test it.
  • Closures can change outside variables, so keep them small and make it obvious what they hold on to.

Mini challenge

Mini challenge: a pricing-rule pipeline

Write pricing rules as lambdas, put them in a list and build a pipeline that applies them one after another.

  • make_discount takes a percent and returns a lambda that reduces a price and rounds to 2 decimals
  • at_least is a curried lambda of (minimum, price), so at_least[10] is a one-argument rule
  • The add_shipping lambda adds 5 to a price
  • apply_rules(price, rules) applies every rule in order
  • Call add_shipping with two arguments and print the ArgumentError message
pipeline.rb
# TODO: make_discount takes a percent and RETURNS a lambda that takes a price
make_discount = nil

# TODO: a two-argument lambda (minimum, price), curried so at_least[10] works
at_least = nil

# TODO: a lambda that adds 5 for shipping
add_shipping = nil

def apply_rules(price, rules)
  # TODO: run every rule on the running price, in order (reduce is handy)
end

# TODO: build [half price, at least 10, shipping] and print the result for 12 and 100
# TODO: call add_shipping with two arguments, rescue ArgumentError, print the message

Expected: Three lines are printed: 15.00 55.00 rejected: wrong number of arguments (given 2, expected 1)

Show hint

Inside reduce(price) { |running, rule| ... } call rule.call(running). make_discount returns a lambda, so there is a lambda inside a lambda.

Show solution
pipeline.rb
make_discount = ->(percent) { ->(price) { (price * (100 - percent) / 100.0).round(2) } }
at_least = ->(minimum, price) { [price, minimum].max }.curry
add_shipping = ->(price) { price + 5 }

def apply_rules(price, rules)
  rules.reduce(price) { |running, rule| rule.call(running) }
end

rules = [make_discount.call(50), at_least[10], add_shipping]
puts format("%.2f", apply_rules(12, rules))
puts format("%.2f", apply_rules(100, rules))

begin
  add_shipping.call(1, 2)
rescue ArgumentError => e
  puts "rejected: #{e.message}"
end

Quick quiz 1 / 3

What does this print? def first; l = -> { return 1 }; l.call; 2; end and def second; pr = proc { return 1 }; pr.call; 2; end are called with p [first, second].

Quick quiz 2 / 3

What does x = 5; add = ->(n) { n + x }; x = 100; puts add.call(1) print?

Quick quiz 3 / 3

Given pr = proc { |a, b| } and la = lambda { |a, b| }, which call raises ArgumentError?

What to remember

  • A Proc saves code as an object, and lambda? tells a proc from a lambda.
  • A lambda checks arguments strictly like a method, and its return leaves only the lambda.
  • A proc fills in or drops arguments loosely, and its return leaves the enclosing method, which can raise LocalJumpError.
  • A closure holds the variable itself, so it sees later changes; &:name, method(:name), curry and >> make callables easier to use.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Procs, Lambdas & Closures | Thuta Learning