Table of contents
1.
Introduction 
2.
Code Blocks and Iterator
3.
Problem
4.
Solution
5.
Examples of an iterator
6.
Frequently Asked Questions
6.1.
How do we use iterator in Ruby?
6.2.
How do we iterate over the range of a number in Ruby?
6.3.
How do we iterate an array in Ruby?
6.4.
What is an iteration in data structure?
7.
Conclusion
Last Updated: Aug 13, 2025
Medium

Writing An Iterator Over a Data Structure In Ruby

Author Yuvati Mankar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

Iterating over objects is an abiding problem for coders. Fortunately, all modern programming languages have an abundance of looping tools, and Ruby is no exception. This article will explain an iterator over a Data Structure in Ruby. Before moving forward, we would like to introduce some of the looping tools in the array.

Some simple looping tools present in ruby are: While loop, For...Do loop, Until, Arrays, Each, Each with Index, Map, Select, and inject.

Code Blocks and Iterator

Code Block is an object that consists of Ruby code, and consists of the context necessary to execute the ruby code. Code blick is a method with no name. Many languages have something like code blocks in ruby, such as C++’s function objects, C’s function pointer, Python’s lambdas, and java’s anonymous inner class. Ruby cannot be written without code blocks, it is very essential to this programming language. 

Example:

[1,2,3].each { |i| puts i } 
# 1 
# 2 
# 3
You can also try this code with Online Ruby Compiler
Run Code

 

So in this blog, we are going to see the problem of writing iterating over data structure with the help of code blocks. 

Problem

Let's say we have created a custom data structure, and we want to implement "each" method for it, or we want to implement an unusual way of iterating over an existing data structure.

Solution

Usually, complex data structures are designed out of the basic data structures like arrays, hashes, and so on. And all of the basic data structures have defined the "each" method. 

Below is the simple tree data structure. A tree data structure contains a list of children and a single value. 

class Tree
attr_reader :value
def initialize(value)
@value = value
@children = []
end
def <<(value)
subtree = Tree.new(value)
@children << subtree
return subtree
end
end
You can also try this code with Online Ruby Compiler
Run Code

 

And, now below is the code to create a specific Tree:

tr = Tree.new("Parent")
child1 = tr << "Child 1"
child1 << "Grandchild 1.1"
child1 << "Grandchild 1.2"
child2 = tr << "Child 2"
child2 << "Grandchild 2.1"
You can also try this code with Online Ruby Compiler
Run Code

Now, the question is how we can use iterator over this data structure? As we can see, the tree is defined recursively, so it is valid to use an iterator over it recursively. The implementation of Tree#each yields the value stored in the tree, then iterates over its children and recursively calls Tree#each on every child tree.

class Tree
def each
yield value
@children.each do |child_node|
child_node.each { |e| yield e }
end
end
end
You can also try this code with Online Ruby Compiler
Run Code

Examples of an iterator

The effortless way to build an iterator is recursive, which means using smaller iterators until we have covered all the elements in a data structure. But there is no guarantee that those iterators are always there or they are present there but giving you elements in the wrong order, in such a case, we will need to write a loop ourselves.

In ruby, Traditional loops are outdated because enumerable iterators are more convenient, but when we are writing an iterator, we are left with no choice but to use a loop. Below is the example showing how to use a while loop to iterate from both sides:

class Array
  def each_from_both_sides()
  front_index = 0
  back_index = self.length-1
  while front_index <= back_index
  yield self[front_index]
  front_index += 1
  if front_index <= back_index
  yield self[back_index]
  back_index -= 1
  end
  end
  end
end


%w{Curses! been again! foiled I've}.each_from_both_sides { |x| puts x }
# Curses!
# I've
# been
# foiled
# again!
You can also try this code with Online Ruby Compiler
Run Code

 

Now, there are two more simple iterators; first one submits each element numerous times in a row:

module Enumerable
  def each_n_times(n)
  each { |e| n.times { yield e } }
   end
end

%w{Hello Echo}.each_n_times(3) { |x| puts x }
# Hello
# Hello
# Hello
# Echo
# Echo
# Echo
You can also try this code with Online Ruby Compiler
Run Code

 

And the other returns the element of an Enumerable in random order:

module Enumerable
def each_randomly
(sort_by { rand }).each { |e| yield e }
end
end

%w{Eat at Joe's}.each_randomly { |x| puts x }
# Eat
# Joe's
# at
You can also try this code with Online Ruby Compiler
Run Code

Frequently Asked Questions

How do we use iterator in Ruby?

Iterator is an idea that is used in object-oriented programming languages. Iteration simple means doing one thing multiple times like a loop. The simplest iterator is the loop method.

How do we iterate over the range of a number in Ruby?

For iterating over the range of a number in Ruby, each() method is used.Syntax: range1.each(|el| block).

How do we iterate an array in Ruby?

The simplest and most popular way to iterate individual items in the array is the Ruby Enumerable#each method.

What is an iteration in data structure?

Iteration is the process in which the set of instructions or structures are repeated several times until the conditions are met.

Conclusion

In this article, we have seen how to create an iterator over a data structure in ruby. We started with an introduction, saw the problem and its solution, and then saw some examples of iterators over a data structure in ruby.

If you want to learn more on such topics, you can visit our website, Coding Ninjas!

You can also consider our Online Coding Courses such as the DSA in PythonC++ DSA CourseDSA in Java Course to give your career an edge over others.

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

Happy learning!

Live masterclass