Ruby Iterators
# Ruby Iterators
Simply put: iteration means doing the same thing repeatedly, so an iterator is used to do the same thing multiple times.
Iterators are methods supported by _collections_. An object that stores a group of data members is called a collection. In Ruby, Arrays and Hashes can be called collections.
Iterators return all elements of a collection, one after another. Here we will discuss two iterators, _each_ and _collect_.
## Ruby _each_ Iterator
The each iterator returns all elements of an array or a hash.
## Syntax
collection.each do |variable| code end
Executes _code_ for each element in the _collection_. Here, the collection can be an array or a hash.
## Example
#!/usr/bin/ruby ary = [1,2,3,4,5]ary.each do |i| puts i end
[Try it Β»](#)
The output of the above example will be:
12345
The _each_ iterator is always associated with a block. It returns each value of the array to the block, one by one. The value is stored in the variable **i** and then displayed on the screen.
## Ruby _collect_ Iterator
The _collect_ iterator returns all elements of a collection.
## Syntax
collection = collection.collect
The _collect_ method is not always associated with a block. The _collect_ method returns the entire collection, regardless of whether it is an array or a hash.
### Example
## Example
#!/usr/bin/ruby a = [1,2,3,4,5]b = Array.new b = a.collect{ |x|x } puts b
[Try it Β»](#)
The output of the above example will be:
12345
**Note**: The _collect_ method is not the correct way to copy an array from one to another. There is another method called _clone_, which is used to copy an array to another array.
When you want to perform some operation on each value to get a new array, you typically use the collect method. For example, the following code will generate an array whose values are 10 times the values in a.
## Example
#!/usr/bin/ruby a = [1,2,3,4,5]b = a.collect{|x| 10*x} puts b
[Try it Β»](#)
The output of the above example will be:
1020304050
YouTip