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.
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)
Output:
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"}
Output:
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.