Table of contents
1.
Introduction
2.
Custom Iterators in Ruby
3.
Passing Argument in Custom Iterators
4.
Frequently Asked Questions
4.1.
In Ruby, what is the yield statement?
4.2.
What exactly are Ruby iterators?
4.3.
In Ruby, how many iterators are there?
4.4.
How are blocks written in Ruby?
4.5.
What exactly are Ruby blocks?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Writing Custom Iterators in Ruby

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

Introduction

Ruby has various types of iterators available like each, times, upto, and each_index, but sometimes it happens that these built-in methods do not work, and we have to create our own iterators. We will learn about the concepts of custom iterators in Ruby. We will start with introducing the iterators with an example and then introduce custom iterators.

Ruby Custom Iterators

So, tighten your sleeves, and let’s get started with the custom iterators in ruby.

Custom Iterators in Ruby

Before learning about custom iterators, we will first define iterators and discuss an example. An iterator is an object that can loop over elements to give the iterative result. 

For example, If we want to print a name five times, then this can be done either manually by writing the print statement five times or by looping over a print statement five times.

#!/usr/bin/ruby
# Code for simple iterators in Ruby to print the square of a number.
num = [10, 8, 6, 2, 5]
square_num = []

num.each do |x|
square_num << x**2
end

puts(square_num)
You can also try this code with Online Ruby Compiler
Run Code


Output:

Output: Custom Iterators

An iterator method is distinguished by the fact that it executes a block of code connected with the method invocation. We can accomplish this via the ‘yield’ statement. There may be situations when the built-in Ruby iterators are insufficient. Fortunately, Ruby makes it quite simple to create your own iterator.

#!/usr/bin/ruby
# Code for custom iterators in Ruby
def sblock
   puts "Inside method"
   yield
   puts "Still inside method"
   yield
end
sblock {puts "Inside the block"}
You can also try this code with Online Ruby Compiler
Run Code


Output:

Output: Custom Iterators

Explanation:

As we can see, the block is called by invoking the method of the same name, ‘sblock’. When we first invoke ‘sblock’, the method begins and the "inner method" is invoked. The ‘yield’ then transfers duty to the block. When this block completes, we return to the original approach. When the yield is called again, this process is repeated.

Passing Argument in Custom Iterators

To give argument values to the block, we will use a comma-separated list of expressions after the ‘yield’ statement. The parameter values, like method invocation, can optionally be contained in parentheses. 

The ‘yield’ function is demonstrated in the following simple iterator:

#!/usr/bin/ruby
# Code for Passing argument in custom iterators in Ruby
def sequence(s1, t1, u1)
   x = 0
while(x < s1)
   yield t1*x + u1
   x += 1
end
end
sequence(6, 8, 4) {|y| puts y }
You can also try this code with Online Ruby Compiler
Run Code


Output:

Output: Passing Argument

Here's another specified situation of a custom iterator in action. Assume we're creating a game that needs to determine whether or not a character's name is valid. We're only interested in character names that have more than three characters.

#!/usr/bin/ruby
characterNames = ['Paul', 'Ada', 'Jonathan', 'Noah', 'Ben']

def characterCheckerValidity(character_names)
   character_names.each do |character_name|
       puts "Is the name '#{character_name}' a valid character?"
       yield(character_name)
   end
end

characterCheckerValidity(characterNames) do |character_name|
   if character_name.length > 3
       puts "You can set this name as it is a valid character name :)"
   else
       puts "You cannot set this name as it is an invalid character name :("
   end
end
You can also try this code with Online Ruby Compiler
Run Code


Output:

Output: Checking Validity

Frequently Asked Questions

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 present in Ruby are- each Iterator, times Iterator, upto and downto Iterator, step iterator, and each_line Iterator.

How are blocks written in Ruby?

Curly braces or a do-end statement enclose blocks. Do-end is typically used for blocks that cross multiple lines, whereas for blocks that only cross one line. Arguments for blocks should be defined between two pipe ‘|’ Characters.

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.

Conclusion

In this article, we have extensively discussed the concept of custom iterators in Ruby. We started with the introduction of iterators and custom iterators in Ruby and concluded with examples and passing arguments in custom iterators.

After reading about the custom 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 Blocks and Iterators in RubyExternal Iterators in Ruby, and Hashes in Ruby.

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 capacity in coding, you may check out the mock test series and participate in the contests hosted on the Coding Ninjas Studio website. But if you have just started learning and are looking for questions asked by tech giants like Amazon, Microsoft, Google, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

You may also consider our courses to give your career an edge over others!

Thank You

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

Happy Learning!

Live masterclass