Procs, lambdas and blocks

One of my students at Ironhack asked me about blocks and procs so I'll take the chance to write a post in the blog.

A proc is a block of code that we can store for later use. This is the most basic form they might take.

This will output Hi!!! in the standard output.

We have a syntactic sugared form for this

But we also have lambdas that have a similar syntax

We can also pass parameters to both of them:

This will output

We have also another syntactic form for lambdas which is used very often

Then, what are the differences between a block and a lambda? There are two of them.

If you run the proc without the parameter it will set it to nil

Outputs:

If you run the lambda without the parameter:

this will throw an exception

There is also a second difference that can be seen in the following script:

This outputs

This is because the return into the proc affects containing method and the return into the lambda affects only the lambda itself.

There is also a third inhabitant into this chunk-of-code world. It is the block. A Block is also a piece of code but in this case it is not an object and we can only use it encapsulated in a Proc. We can receive a block of code as a parameter in every function.

Since a block of code is not an object we need another special form to invoke it. This is the yield you can find there.

Anyway we can encapsulate that block and use it like any other object.

This will output:

Leave a Reply

Your email address will not be published. Required fields are marked *