Table of contents
1.
Introduction
2.
Ruby Blocks
3.
The yield statement
3.1.
Passing Parameters with a yield statement 
4.
Block Variables
5.
BEGIN and END Blocks
6.
Ruby Iterators
7.
Ruby Each Iterator
8.
Ruby Time Iterators
9.
Ruby Upto and Downto Iterators
10.
Ruby Step Iterators
11.
Frequently Asked Questions
11.1.
What exactly are Ruby blocks?
11.2.
How many different ways a Ruby block may be written?
11.3.
In Ruby, what is the yield statement?
11.4.
What exactly are Ruby iterators?
11.5.
In Ruby, how many iterators are there?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

Blocks and Iterators in Ruby

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will learn about some essential Blocks and Iterators in Ruby concepts. We will also learn about Block variables, BEGIN and END; this blog will help you understand more about Blocks and Iterators in Ruby from a very basic level and helps you to improve your knowledge of Blocks and Iterators in Ruby. Are you familiar with Blocks and Iterators in Ruby, if not then don’t worry Coding Ninjas is always there for you. Well, let's start our topic with some common definitions of topics.

Blocks and Iterators in Ruby

Ruby Blocks

Other programming languages refer to Ruby code blocks as closures. It comprises a series of codes that are always separated by braces or written between doing..end. The brackets syntax takes priority over the do..end syntax every time. Braces take priority overdo and vice versa.

Ruby has a concept of Block, which is:

  • A block can be written in two ways:
    1. Multi-line between doing and end (multi-line blocks are not inline).
    2. Inline between braces
  • Both are the same and serve the same purpose.
  • To call a block, you must have a function with the same name as the Block.
  • A function is always used to invoke a block. Blocks can have their arguments.

 

Syntax:

block_name{
statement1
statement2
…….
}
You can also try this code with Online Ruby Compiler
Run Code

 

Now that we've defined Blocks and their syntax let's look at one of the most significant topics in Blocks: the yield statement.

The yield statement

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

Let's break it down with an example to help with understanding.

Def met
  puts, "This is Ruby."
  Yield
  puts, “We will be back to Ruby.”
  yield
end
met {puts “This is Block”}
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

This is Ruby
This is Block
We will be back at Ruby
This is Block

 

In this example, when we reach the yield line during the execution of the met method, the code inside the Block is performed. When the block execution is complete, the code for the met method resumes.

Passing Parameters with a yield statement 

Let's understand it with the help of an Example:-

def test
   yield 5
   puts "We are in Ruby test."
   yield 10
end
test {|i| puts "We are in the block #{i}"}
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

We are in the block 5
We are in the Ruby test
We are in the Block 10

 

In this example, the yield statement is written first, followed by parameters. You may even pass several parameters. To accept the arguments, you add a variable between two vertical lines (||) in the Block. As a result, the yield 5 statement in the preceding code passes the number 5 as a parameter to the text block.

Consider the following statement:

test {|i| puts "We are in the block #{i}"}

 

In this case, the variable receives the value 5. Consider the following puts statement:

puts "We are in block #{i}."

 

This puts command produces the output.

You are in the block 5

 

If you wish to pass many parameters, the yield statement becomes

yield a, b

 

and the Block is −

test {|a, b| statement}

 

Commas will be used to separate the parameters.

As we are done with the Yield statement, now let's move on to Block variables.

Block Variables

We can use the same variable both within and outside of a block parameter. Consider the following example.

x= “Outer variable”
3.times do |x|
puts “Inside block: #{x}”
end
puts “Outside block: #{x}”
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Inside Block: 0
Inside Block: 1
Inside Block: 2
Outside Block: Outer variable

 

In this example, we use the same variable both within and outside the Block as block argument x.

BEGIN and END Blocks

Every Ruby source file can include code blocks that will be executed both when the file is loaded (the BEGIN blocks) and after the program has completed running (the END blocks).

A program may have several BEGIN and END blocks. BEGIN blocks are processed in the order in which they are encountered. END blocks are performed backward.

We've already covered Blocks, so let's move on to Iterators, which will cover the second part of this blog.

Ruby Iterators

Iterator is a term used in object-oriented programming. Iteration is the repetition of a single action, similar to a loop.

The loop method is the most basic Iterator. They return all the components of a collection one by one. Arrays and hashes are examples of collections.

There are mainly four types of Iterators which are Each, Upto & Downto, Step, and Time Iterators. Let's define each one by one.

Ruby Each Iterator

Each Iterator in Ruby returns all the items of a hash or array.

Syntax:

Collection.each do |variable|
      Code…
end
You can also try this code with Online Ruby Compiler
Run Code

 

Code is executed for each element in the collection. The collection might be an array or a Ruby hash in this case.

Let's take an example for better understanding: -

ary = [1,2,3,4,5]
ary.each do |i|
   puts i
End
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

1
2
3
4
5

 

Each Iterator is always associated with a block. It returns each array value to the Block one by one. The value is saved in the variable I before being displayed on the screen.

We defined Each Iterator till now, and let's move on to the second type, which is the time Iterator.

Ruby Time Iterators

The time iterator executes a loop a specified number of times. The loop will begin at zero and continue until one less than the provided value is reached.

Syntax:

x.times do |variable|
  Code…
end
You can also try this code with Online Ruby Compiler
Run Code

 

To iterate the loop, we must define a number in place of x.

Ruby Upto and Downto Iterators

An upto iterator loops over the numbers x and y.

Syntax:

x.upto(y) do |variable|  
     code  
end  
You can also try this code with Online Ruby Compiler
Run Code

Ruby Step Iterators

A step iterator is used to iterate across a range while skipping over it.

Syntax:

(controller).step(x) do |variable|  
    code  
end  
You can also try this code with Online Ruby Compiler
Run Code

 

In this case, x represents the range that will be skipped during iteration.

We recently finished Blocks and Iterators in Ruby, and I hope you understand it well. Let's see whether you recall what we've covered so far.
Check out this problem - Redundant Braces

Frequently Asked Questions

What exactly are Ruby blocks?

Other programming languages refer to Ruby code blocks as closures. It is made up of a series of codes that are always separated by braces or written between do...end.

How many different ways a Ruby block may be written?

There are two methods to write a block are several lines between doing and end and Inline between the braces

Both are identical and serve the same purpose.

In Ruby, what is the yield statement?

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

What exactly are Ruby iterators?

Iterator is a term used in object-oriented programming. Iteration is the repetition of a single action, similar to a loop.

The loop method is the most basic Iterator. They return all the components of a collection one by one. Arrays and hashes are examples of collections.

In Ruby, how many iterators are there?

The iterators in Ruby are each Iterator, times Iterator, upto and downto Iterator, step iterator, and each_line Iterator.

Conclusion

In this article, we learned about Blocks and Iterators in Ruby, including Ruby Blocks Variables, BEGIN and END Blocks, Each Iterator, and Ruby Time Iterators. Blocks and Iterators in Ruby are significantly important topics for Interviewers. I hope you all understand about Blocks and Iterators in Ruby.  After reading about Blocks and Iterators in Ruby, are you not feeling excited to read/explore more articles on the topic of Ruby? Don't worry; Coding Ninjas has you covered. To learn, see Ruby OOPsTainting Objects in Ruby, and Object References in Ruby. You can also refer to the Official RubyRubyOfficial DocumentationRuby FAQ, and Ruby Koans.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Live masterclass