Ruby Iterators
Iterator is a concept used in object-oriented language. Iteration means doing one thing many times like a loop.
The loop method is the simplest iterator. They return all the elements from a collection, one after the other. Arrays and hashes come in the category of collection.
Ruby Each Iterator
The Ruby each iterator returns all the elements from a hash or array.
Syntax:
Here collection can be any array, range or hash.
Example:
Output:
Ruby Times Iterator
A loop is executed specified number of times by the times iterator. Loop will start from zero till one less than specified number.
Syntax:
Here, at place of x we need to define number to iterate the loop.
Example:
Output:
Ruby Upto and Downto Iterators
An upto iterator iterates from number x to number y.
Syntax:
Example:
Output:
Ruby Step Iterator
A step iterator is used to iterate while skipping over a range.
Syntax:
Here, x is the range which will be skipped during iteration.
Example:
Output:
Ruby Each_Line Iterator
A each_line iterator is used to iterate over a new line in a string.
Example:
Output: