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
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
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 :
Likewise, we can sum the value of first ten numbers by,
Ruby: Step Iterator
It's somewhat similar to upto
iterator.
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 :
To print the sum of odd numbers up to 10
The output of the above program is :
Remember, Iterators provide more flexibility when compared to a while
and do while
loop in traditional programming languages.