Iterator in Ruy

2020-10-05 hit count image

Let's see how to use the Iterator to handle the arrays more comfortable in Ruby.


In this blog post, we’ll see what the Iterator is, and how to use the Iterator to handle arrays easily.


The Iterator is a method to iterate over each element of an object with multiple elements, such as an array. In this blog post, I will introduce the frequently used iterators.

each method

Each element of the array is assigned to |variable| and iterates over it.

<Array>.each { |<Variable>|
  Repeat actions

You can use each method like below.

fruits = ['apple', 'banana', 'orange']
fruits.each {|fruit|
  puts fruit

times method

If the number of iterations is fixed, you can use times method.

4.times {
  puts 'Hello world'

In Ruby, the number is also an object, so you can use times method like above.

loop method

The loop method performs iteration without termination.

i = 0
loop {
  i += 1
  puts 'Hello world'
  if i == 4

You can terminate loop by using break like above, but If you don’t, it will be into the infinite loop, so be careful to use this.

Iterators usage

When you handle the Arrays, it is more convenient to use iterators.

each_with_index method

If you need the Index in the Arrays, you can use each_with_index method.

fruits = ['apple', 'banana', 'orange']
fruits.each_with_index {|fruit, i|
  puts "#{i}: #{fruit}"


You can also use the Iterators in Hash.

fruits = {:Apple => 'apple', :Banana => 'banana', :Orange => 'orange'}
fruits.each {|key, value|
  puts "#{key}: #{value}"


You can use the Iterators in the File class. If you use the Iterator in the File, you can get the line of the text file.

file ="test.txt")
file.each {|line|
  puts line

Define the iterator

When you define the method, you can define the Iterator by using yield.

def temp
  yield 10
  yield 'Hello'

temp {|value|
  puts value * 2
# 20
# HelloHello


We’ve seen what the iterator is, and how to use the iterator. Also, we can define a new iterator when we need. From now on, let’s use the Iterators to handle Arrays, Hash, and so on.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!