Introduction

The code between { and } or do and end is a code block.

For example:

Demo

x = [1, 2, 3] 
x.each { |y| puts y }

Result

The each method accepts a single following code block.

The code block is defined within the { and } symbols or, alternatively, do and end delimiters:

Demo

x = [1, 2, 3] 
x.each do |y| #   w ww .j  ava 2  s .c  o m
 puts y 
end

Result

Ruby block is a unit of code that works like a method with no name.

What Is a Block?

Consider this code:

3.times do |i|
   puts( i )
end

The following is an alternative form of the previous code.

This time, the block is delimited by curly brackets rather than by do and end.

3.times { |i|
   puts( i )
}

times is a method of Integer, which iterates a block "int times, passing in values from 0 to int -1."

The two above code examples are functionally identical.

A block can be enclosed either by curly brackets or by the do and end keywords.

Related Topic