RubyGuides
Share this post!

The Ultimate Guide to Blocks, Procs & Lambdas

In this post you will learn everything you need to know about Ruby procs, blocks & lambdas.

Understanding Blocks

Blocks are very prevalent in Ruby, you can think of them as little anonymous functions that can be passed into methods.

Blocks are enclosed in a do / end statement or between brackets {}, and they can have multiple arguments. The argument names are defined between two pipe | characters.

If you have used each before, then you have used blocks!

Here is an example:

So how does a method work with a block, and how can it know if a block is available? Well, to answer the first question, you need to use the yield keyword. When you use yield, the code inside the block will be executed.

Yield can be used multiple times, which will result in the block being executed as many times as you call yield.

It is also possible to use yield with any number of arguments. These arguments can then be used by the block.

Blocks can also be explicit instead of implicit. What this means is that you can name the block and pass it around if you need to.

Here is an example:

If you try to yield without a block you will get a no block given (yield) error. You can check if a block has been passed in with the block_given? method.

Lambdas vs Procs

Procs & lambdas are a very similar concept, one of the differences is how you create them.

In fact, there is no dedicated Lambda class. A lambda is just a special Proc object. If you take a look at the instance methods from Proc, you will notice there is a lambda? method.

The syntax for defining a Ruby lambda looks like this:

You can also use the word lambda instead of ->.

Defining a lambda won’t run the code inside it, you need to use the call method for that.

Example:

There are other ways to call a lambda, it’s good to know they exist, however, I recommend sticking with call for clarity.

Lambdas can also take arguments, here is an example:

If you pass the wrong number of arguments to a lambda, it will raise an exception, just like a regular method. But that’s not the case with procs, as demonstrated in the following example.

You can also use proc instead of Proc.new

Another difference between procs and lambdas is how they react to a return statement. A lambda will return normally, like a regular method. But a proc will try to return from the current context.

If you run the following code, you will notice how the proc raises a LocalJumpError exception. The reason is that you can’t return from the top-level context.

Try this:

If the proc was inside a method, then calling return would be equivalent to returning from that method. This is demonstrated in the following example.

Here is a summary of how procs and lambdas are different:

  • Lambdas are defined with -> {} and procs with Proc.new {}.
  • Procs return from the current method, while lambdas return from the lambda itself.
  • Procs don’t care about the correct number of arguments, while lambdas will raise an exception.

Taking a look at this list, we can see that lambdas are a lot closer to a regular method than procs are.

Closures

Procs & lambdas also have another special attribute. When you create a Ruby proc, it captures the current execution scope with it.

This concept, which is sometimes called closure, means that a proc will carry with it values like local variables and methods from the context where it was defined.

They don’t carry the actual values, but a reference to them, so if the variables change after the proc is created, the proc will always have the latest version.

Let’s see an example:

In this example we have a local count variable, which is set to 1. We also have a proc named my_proc, and a call_proc method which runs (via the call method) any proc or lambda that is passed in as an argument.

What do you think this program will print?

It would seem like 500 is the most logical conclusion, but because of the ‘closure’ effect this will print 1.

This happens because the proc is using the value of count from the place where the proc was defined, and that’s outside of the method definition.

The Binding Class

Where do Ruby procs & lambdas store this scope information?

Let me tell you about the Binding class…

When you create a Binding object via the binding method, you are creating an ‘anchor’ to this point in the code. Every variable, method and class defined at this point will be available later via this object, even if you are in a completely different scope.

Example:

In other words, executing something under the context of a binding object, is the same as if that code was in the same place where that binding was defined (remember the ‘anchor’ metaphor).

You don’t need to use binding objects directly, but it’s still good to know this is a thing 🙂

Wrapping Up

In this post you learned how blocks work, the differences between Ruby procs & lambdas and you also learned about the “closure” effect that happens whenever you create a block.

One thing I didn’t cover is the curry method. This method allows you to pass in some or all of the required arguments. If you only pass in a partial number of arguments you will get a new proc with these arguments already ‘pre-loaded’, when all the arguments are supplied then the proc will be executed.

I hope you enjoyed this post! Don’t forget to subscribe in the form below and share this with your friends 🙂

11 comments
Gagan says last year

Well explained!

    Jesus Castello says last year

    Thank you 🙂

Kaloyan Yordanov says last year

A wonderful article, Jesus, so nicely written!

    Jesus Castello says last year

    Thanks for reading 🙂

ttw (@ttwo32) says last year

Good article, Jesus. I think that it is important to understand differences between lambda and proc. This article describe differences politely by coding example, so readers easily understand.
And block is a feature to incarnate Closure.

    Jesus Castello says last year

    Thanks for your comment 🙂

vizvamitra says last year

There is also another interesting behavior of procs:

def proc_from
Proc.new
end

proc = proc_from { “hello” }
proc.call #=> “hello”

If Proc.new is called within a method with an attached block, that block is converted to the Proc object.
(example from http://ruby-doc.org/core-2.2.0/Proc.html)

Sangam Gupta says last year

Very helpful, thank you. However there is one think confusing, I checked Kernel module and I see lambda method which is creating Proc object but you mentioned, lambda is a special object of Proc class. Your thoughts?

    Jesus Castello says last year

    The lambda method on Kernel is the same as using the -> syntax for defining a lambda.

Sangam Gupta says last year

Thank you, I had the same assumption 🙂

Robert says last year

Good article: clear and gives a good overview!

Some minor nitpicking:
– Blocks are anonymous functions.
– Usually the alternative delimiters to do…end are called “curly braces” or “curly brackets” – “brackets” are (…) if I’m not mistaken.
– There is another, older and thus potentially more compatible syntax to create lambdas: lambda {|arg| …} and lambda do |arg| … end

Comments are closed