Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 134 ยท Methods and Blocks

Procs and Lambdas

Understand Ruby procs and lambdas - how they differ in arguments and return, arity, closures, curry, composition, Method objects and Symbol#to_proc, with examples.

A block is code you pass to a method, but it is not an object: you cannot put it in a variable or a hash. Ruby gives you two object forms of the same idea. A Proc is a block turned into an object. A lambda is a Proc with stricter, method-like rules. Both can be stored, passed around, returned from methods and called whenever you like, which makes them the building blocks of callbacks, strategies, validators and small functional pipelines.

Most of this lesson is about the differences between procs and lambdas, because that is where the surprises are. There are exactly two: how they treat arguments and what return does. You will also meet arity, curry, function composition with >> and <<, Method objects and the trick behind &:symbol.

Creating procs and lambdas

Ruby Four ways to make a callable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The stabby syntax ->(args) { body } is what modern Ruby code uses for lambdas; lambda { } still appears in older code. All four calling styles (call, .(), [], yield) are the same. Ruby has no separate lambda class: a lambda is a Proc whose lambda? is true.

Difference 1: argument checking

A lambda behaves like a method: pass the wrong number of arguments and it raises an error. A proc behaves like a block: missing arguments are nil, extras vanish, and one array argument is spread.

Ruby Lenient proc, strict lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Those four lines all work. Now break the lambda on purpose.

Ruby A lambda checks its arguments (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line of the error is main.rb:1:in 'block in <main>': wrong number of arguments (given 1, expected 2) (ArgumentError); Ruby 4 follows it with a small excerpt showing both the call site and the lambda. This strictness is a feature. A lambda is a function, and a function with the wrong arguments is a bug you want to hear about immediately.

Difference 2: what return means

In a proc, return returns from the method that created the proc, exactly like return inside a block. In a lambda, return just ends the lambda and hands a value back to the caller.

Ruby return in a proc and in a lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

with_proc returns :from_proc because the return inside the proc leaves the whole method. In with_lambda the lambda ends, the method continues and returns :after_lambda. Two related rules follow:

  • Use next inside a proc if you only want to leave the proc itself.
  • A proc whose defining method has already returned cannot return at all. You saw the LocalJumpError: unexpected return in Blocks. A lambda has no such problem, which is why lambdas are the safe choice for anything stored for later.

Rule of thumb: when you need to keep a piece of code in a variable, constant, hash or instance variable, write a lambda. Use plain blocks (and procs captured with &block) for code that runs while the method is still active.

Arity: how many arguments?

arity tells you how many arguments a callable expects. A required-only callable returns the exact count. For a lambda, optional arguments make the number negative: -(required + 1). (A plain proc with only optional parameters reports the required count, as the last lines show.)

Ruby arity and parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

parameters lists each parameter with its kind: :req, :opt, :rest, :keyreq, :key, :block. Libraries use it to adapt to your callable. For example, a framework can call your lambda with one argument or two depending on arity.

Closures: remembering their surroundings

Procs and lambdas are closures. They carry the variables that were visible where they were created, even after that scope is gone. The variables are shared, not copied.

Ruby A counter built from a closure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each call to make_counter creates a fresh count, and the two lambdas created in it share that variable. The last example prints 50, not 15: the lambda captured the variable, not its value at the time. Closures and Binding explores scope rules and how to inspect a closure's environment.

Functions that return functions

Because lambdas are values, a method can build and return them.

Ruby A lambda factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The &double passes the lambda as the block of map. A lambda used this way keeps its strictness, so it must accept exactly the arguments map yields (one here). With a hash, a lambda is a clean "strategy table": the dictionary maps a name to behavior.

Currying and partial application

curry turns a function of several arguments into a chain of functions of one argument each, so you can supply arguments in several steps.

Ruby curry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A curried lambda waits until it has all required arguments, then runs. Fixing the first arguments (greet["Hello"]) creates a specialised function, known as partial application. For variable-arity callables pass the count: proc.curry(3).

Composition with >> and <<

f >> g builds a new callable that calls f first and passes the result to g. f << g does it the other way round. It reads like a pipeline.

Ruby Composing callables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You can compose procs, lambdas, Method objects and anything else that responds to call. The composed callable is itself a Proc, so you can compose it again or pass it with &.

Method objects and Symbol#to_proc

obj.method(:name) gives you a Method object: the method as a callable that remembers its receiver. to_proc turns it into a lambda.

Ruby Method objects and &:symbol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

&:upcase works because & calls to_proc on the symbol; Symbol#to_proc returns a lambda that sends the symbol as a message to its first argument. An UnboundMethod (from instance_method) is a method without a receiver; you bind it to an object of the right class before calling. Reflection and Introspection shows what else you can do with them.

The call protocol: anything with call

Callers rarely care whether you pass a lambda, a proc or a method. They only need call. Your own objects can join in:

Ruby Any object with call works

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A common library convention is "accept anything that responds to call". It lets users pass a lambda for quick jobs and a full class when the logic grows. Because Discount defines to_proc, it also works after &.

Pitfalls

  • proc and Proc.new without a block raise ArgumentError (tried to create Proc object without a block). Always give a block.
  • A lambda used as a block through & still enforces its arity. {a: 1}.each(&->(k, v) { }) raises ArgumentError (given 1, expected 2) because each yields one pair, whereas a proc would spread it.
  • Do not store procs that use return. Convert to a lambda or use next.
  • Closures keep objects alive. A long-lived lambda holds on to every variable it can see, which can retain large data.
  • Prefer lambdas for callbacks you define as constants or hash values; prefer plain blocks for iteration.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference in argument handling between a proc and a lambda?

    A lambda is checked like a method. A proc treats arguments like a block: missing ones are nil, extras are ignored, and a single array is spread.
  2. 2. Inside a method, p = proc { return 1 }; p.call; 2 - what does the method return?

    return inside a proc returns from the enclosing method, so the method returns 1 and the final 2 is never reached. With a lambda it would return 2.
  3. 3. What is ->(a, b = 1) {}.arity?

    With optional arguments arity is -(required + 1). One required argument gives -2.
  4. 4. What does f >> g produce?

    f >> g reads left to right: g.call(f.call(x)). The reverse operator f << g calls g first.
  5. 5. Why does %w[a b].map(&:upcase) work?

    The & operator calls to_proc on its operand. Symbol#to_proc returns a callable that sends the symbol as a method call to its first argument.

Summary

  • A Proc is a block as an object; a lambda (->(x) { }) is a Proc with lambda? true.
  • Lambdas check argument counts and return only leaves the lambda; procs are lenient and return leaves the enclosing method.
  • Call with call, .(), [] or yield; arity and parameters describe the signature.
  • Both are closures: they share the variables of the scope that created them.
  • curry supports partial application; >> and << compose callables.
  • method(:name) gives a Method object, &:sym uses Symbol#to_proc, and any object with call (and optionally to_proc) can play the same role.

Next: Closures and Binding