Home » Ruby Blocks

Ruby Blocks

Ruby code blocks are called closures in other programming languages. It consist of a group of codes which is always enclosed with braces or written between do..end. The braces syntax always have the higher precedence over the do..end syntax. Braces have high precedence and do has low precedence.

A block is written in two ways,

  • Multi-line between do and end (multi-line blocks are niot inline)
  • Inline between braces {}

Both are same and have the same functionality.

To invoke a block, you need to have a function with the same name as the block.

A block is always invoked with a function. Blocks can have their own arguments.

syntax:

Example:

The below example shows the multi-line block.

Output:

Ruby Blocks 1

Below example shows the inline block.

Output:

Ruby Blocks 2


The yield statement

The yield statement is used to call a block within a method with a value.

Example:

Output:

Ruby Blocks 3

While the execution of met method, when we reach at yield line, the code inside the block is executed. When block execution finishes, code for met method continues.

Passing parameters with yield statement

One or more than one parameter can be passed with the yield statement.

Example:

Output:

Ruby Blocks 4


Block Variables

We can use same variable outside and inside a block parameter. Let’s see the following example.

Example:

Output:

Ruby Blocks 5

In this example, we are using same variable inside the block as the block parameter x and outside the block as a variable x.


BEGIN and END block

Ruby BEGIN and END block is used to declare that file is being loaded and file has been loaded respectively.

Example:

Output:

Ruby Blocks 6


Ampersand parameter (█)

The █ is a way to pass a reference (instead of a local variable) to the block to a method.

Here, block word after the & is just a name for the reference, any other name can be used instead of this.

Example:

Output:

Ruby Blocks 7

Here, the block variable inside method met is a reference to the block. It is executed with the call mehtod. The call method is same as yield method.


Initializing objects with default values

Ruby has an initializer called yield(self). Here, self is the object being initialized.

Example:

Output:

Ruby Blocks 8


Next TopicRuby modules

You may also like