About Proc, Lambda and Block
I keep on searching for this topic, so I guess it’s time I put it on my blog.
This is an example of a proc
:
To execute the_proc
, I need to explicityly to use:
You can create a lambda using this syntax:
Just like with proc
you can execute it using one of these three methods:
Differences between lambda
and proc
:
lambda
will raise an error if argument wasn’t provided during the call (if there’s any argument defined in the declaration).proc
will just silently set it to nil for this situation.- For
proc
, if there’s areturn
defined, it’ll return from the enclosing method. But forlambda
, it will just return from thelambda
itself.
So, what is block in Ruby? Using the above example of proc
, a block is
actually the piece of code that sits between those two curly braces, in this
case that would be: puts "proc"; return
.
The only way to get access to the block is through the proc or lambda as block is not an object.
A basic example of block usage would be:
As you can see from the example, we actually don’t have direct access to the
block. In order to get access to that block, we need to wrap it in proc
and
this how you do it:
You can use block.call
or just use the yield
keyword to execute the block.
The biggest benefit of this approach is that we can control in which context
it’s being executed. This is very useful in building DSL.
For e.g, let’s take a look at a simple DSL (that looks like Rails router):