Blocks, procs, lambdas, and methods available in Ruby are collectively called closures.

What is a closure?

Simply put, it’s all the variables referenced in the block that remain accessible for the life of the block even if defined in another scope. It can be defined in one scope and used in another. The best way to remember this is to imagine a closure as a little backpack that stores all the variables that were in scope when the method was created. You can take the backpack to another scope, and use those said variables there because they are still in the backpack.

Ruby has closures in the form of blocksprocs, and lambdas.

How are they different?

Blocks are used for passing, well, blocks of code to methods; procs and lambdas allow storing blocks of code in variables.

A block is simply a chunk of code enclosed between braces or the keywords do and end. You can think of a block as a body of a method. Just as a method, it can take parameters (at the start of the block between vertical bars). Also like a method, the body of the block gets stored away to be called later. They appear in Ruby source code immediately after the invocation of some other method, and you can almost think of them as being one extra parameter passed to the method. Depending on how the block is written, you can pass one or more variables into your blocks.

Let’s look at a simple example:

Image for post

The block is being called for each element of the array. Each element is passed to the block (or yielded) as the num parameter. The variable defined inside the block is local to the block.

We then perform an operation with the help of an iterator. An iterator is simply a method that can invoke a block of code (like the good old each) for each element of a collection (an array, in our case).

What makes blocks interesting is that you can pass parameters to them and receive values from them. In the following example we can see a simple method that returns members of the Fibonacci series up to a certain value:

Image for post

In this example, the yield statement has a parameter whose value is passed to the block. The variable “num” receives the value passed to yield and prints out the sequence.

A block may also return a value to the method. The value of the last expression evaluated in the block is passed back to the method as the value of yield. Let’s take a closer look by dissecting .find:

Image for post

In the above example, each element of the array is passed to the associated block and returns the element if the specified condition is true.

#ruby #closures-functions #programming #function

Ruby Closures for Dummies
1.30 GEEK