A block looks similar to a method in Ruby. Methods consist of a name, but with blocks we don’t need to write a name, and always pass to a method call.
Blocks are a handy and powerful feature in Ruby, and we can use them anywhere.
Blocks are anonymous pieces of code that accept input from arguments and return a value.
We can implement Ruby blocks in two ways:
do-end
statementUsually, Ruby blocks are implemented within the do-end
statement, as they span through multiple lines of code in the program.
block do
#statement-1
#statement-2
#statement-3
.
.
end
{}
curly bracesWe use curly braces to span through a single line of code.
[0, 2, 4].each { |n| puts n }
We can use pipe
|
: (vertical bars) between two characters to define an argument in a block.
We can implement blocks by using the yield
statement. We can invoke a yield
by passing arguments into the block, too. It calls a block within a method using the yield
keyword.
do-end
statementLet’s first look at an example of Ruby blocks enclosed within a do-end
statement.
[1, 2, 3, 'A', 'B', 'C'].each do |n| puts n end
In the above example, the block has an argument n
and puts n
can be described as the body of our block.
The array is iterated one time because of the each
loop and displays the given input.
{}
bracesHere’s an example code for a Ruby block enclosed within {}
curly braces.
[1, 2, 3, 'A', 'B', 'C'].each { |n| puts n * 2 }
We have used the same array list for this example, but the result generated would be different, as the argument of block asks to display the n + 2
th result of each array element.
yield
statementLet’s look at the following code program that uses the yield
keyword to display blocks.
def yield_block puts "Method 01." yield puts "Method 02." yield end yield_block { puts "This is a block with yield statement." }
The above program includes a block named yield_block
that displays two methods and calls the block outside the loop.
RELATED TAGS
CONTRIBUTOR
View all Courses