Signup/Sign In

Iterator in Ruby

Iterators allow us to traverse a range and to do something certain number of times within a range. It's easier to demonstrate Iterator rather than describing it.


Ruby: Times Iterator

Times Iterator example in Ruby

This code executes the statements inside the do block for the number of times given before times keyword. times keyword knows to start from 1 and stop at which the number specified before times keyword.

Here, 5 is given. So, it prints "Hello, World" for 5 times.

Ruby: Upto Iterator

Upto Iterator example in Ruby

It iterates through the range starting from the number specified before the upto keyword and up to the number specified in the upto keyword. In our case, starting from 1 up to 10. For each iteration, it stores the value to the variable x. Using the value in the variable x, we can perform our desired operations by specifying it in the do block.

The output of the above code is :

Upto Iterator example in Ruby

Likewise, we can sum the value of first ten numbers by,

Upto Iterator example in Ruby


Ruby: Step Iterator

Step Iterator example in Ruby

It's somewhat similar to upto iterator.

Step Iterator example in Ruby

It iterates between the range specified by the user. For each iteration it increases the value of the variable x specified by the step counter.

The output of the above program is :

Step Iterator example in Ruby

To print the sum of odd numbers up to 10

Step Iterator example in Ruby

The output of the above program is :

Step Iterator example in Ruby

Remember, Iterators provide more flexibility when compared to a while and do while loop in traditional programming languages.