Blocks, Procs and Lambda

Ruby blocks introduction

Ruby blocks allow a chunk of code to be passed to methods without first storing that chunk of code into any variable.

In the above case { puts "hello" } is the chunk of code that is being passed to method each. As we can see that chunk of code is not stored in a variable first. That’s why some folks say that Ruby blocks are used to pass anonymous code to method. Here by anonymous the only thing they mean is that the chunk of code is not first stored into a variable.

Here is one more example. In this case also the code inside “do end” is a ruby block.

Here are two more examples of ruby blocks.