Skip to content

Using Procs vs Lambas

Last updated on June 4th, 2024 at 06:07 pm

Table of Contents

An example use case

At first glance, Procs and Lambdas can appear to be of little use. What do I need a Proc or Lambda for when I can simply use methods? Basically, Procs and Lambdas are useful when you need executable code to be stored in a variable, which cannot be done with a normal block.

One instance where they can be helpful is where we have to read in a CSV file and validate each column. An example of this is shown below.

First, the validators are set up

And then references on each row using the call method on the Lambda

You could also accomplish the same task using Procs instead of Lambdas

The execution of the validator would be the same.

While Lambdas can be a little faster in execution than Procs, in most cases Lambda would be sufficient.

When to use Procs instead of Lambdas?

One of the key differences between Lambdas and Procs is that a Lambda will strictly enforce the number of parameters it is called with, referred to as Arity, whereas a Proc won’t. For example, the following code will execute without any errors for Procs.

In addition, a Proc can force a non-local return, as in the following example.

This capability could be used, for example, to force an early return when validating a collection of data, as with the following example.

In general, Lambdas are sufficient for the majority of operations and preferred because of their Arity checking and less risk of accidental non-local returns.

Storing Methods in Variables

It is possible, instead of using a Lambda or a Proc, to store a method in a variable and use that.

When to use what….

When would you use a method instead of a Proc or Lambda?

  • You have existing methods that you want to reference and call dynamically
  • You need to reflect on method metadata or preserve the method’s binding to its original context
  • You want to keep the logic encapsulated within the object-oriented design

Use Lambdas and Procs when: