What is a block in Ruby?
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.
Syntax
We can implement Ruby blocks in two ways:
1. Enclosed within do-end statement
Usually, 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
2. Enclosed within {} curly braces
We 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.
The ‘yield’ statement
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.
Code
Example 01
Code using do-end statement
Let’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 nend
Explanation 01
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.
Example 02
Code using {} braces
Here’s an example code for a Ruby block enclosed within {} curly braces.
[1, 2, 3, 'A', 'B', 'C'].each {|n| puts n * 2}
Explanation 02
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 + 2th result of each array element.
Example 03
Block using the yield statement
Let’s look at the following code program that uses the yield keyword to display blocks.
def yield_blockputs "Method 01."yieldputs "Method 02."yieldendyield_block {puts "This is a block with yield statement."}
Explanation 03
The above program includes a block named yield_block that displays two methods and calls the block outside the loop.
Free Resources