Blocs, Procs, and Lambdas

Blocks, Procs and lambdas (also know as closures in Computer Science) are one of the most powerful aspects of Ruby, and also one of the most misunderstood. I will attempt to explains the similarities and differences.

First Up Blocs

A block is just a bit of code between do..end or {}. It's not an object on its own, but it can be passed to methods like .each or .collect.

We've seen this in action.

Nothing new here.

Now Procs

A proc is a saved block we can use over and over. Just like you can give a bit of code a name and turn it into a method, you can name a block and turn it into a proc. With procs you write your code once and use it many times. That way keeping your code D.R.Y (Don't Repeat Yourself).

Last, but not least, Lambdas

Like procs lambdas are objects. With the exception of some syntax differences, procs and lamdas are essentially the same.

Lambdas vs. Procs

Eventhough procs and lambdas sport stricking similarities there are two main differences.

First, lambdas check the number of arguments, while procs do not.

In contrast, procs don’t care if they are passed the wrong number of arguments.

Second, Lambdas and procs treat the ‘return’ keyword differently.

‘return’ inside of a lambda triggers the code right outside of the lambda code

‘return’ inside of a proc triggers the code outside of the method where the proc is being executed

Summary Differences

  1. Procs are objects, blocks are not
  2. A proc is a saved block we can use over and over.
  3. A lambda is just like a proc, only it cares about the number of arguments it gets and it returns to its calling method rather than returning immediately.