An iterator is nothing but a collection of methods supported. An object that stores a set of data members is called a collection. In Ruby, arrays and hashes can be called collections.
The iterator returns all the elements of a collection, one after the other. We'll talk about two iterators, here, for each collection. Let's take a look at these details.
Ruby each iteration:
Each iterator returns all the elements or hashes of an array.
Grammar:
Collection.each do |variable|
Code End
Code that executes for each element in the collection. Here the collection may be an array or a ruby hash.
Example:
#!/usr/bin/ruby
ary = [1,2,3,4,5]
Ary.each do |i|
Puts I end
This will produce the following results:
You always associate each iteration with the block. It returns each value of the array, blocks by block. The value is stored in the variable i and then displayed on the screen.
Ruby Collect iterations:
The collected iterator returns all the elements of a collection.
Grammar:
Collection = Collection.collect
Collection methods do not always require blocks. The collection method returns the entire collection, whether it is an array or a hash.
For example:
#!/usr/bin/ruby
a = [1,2,3,4,5]
B = array.new
B = A.collect
puts b
This will produce the following results:
Note: The collection method is not the correct way to do the replication between the arrays. There is another method called cloning, which should be replicated to another array using one array.
You usually use the collection method when you want to do something with each value to get the new array. For example, this code contains 10 times times each value, resulting in an array of B.
#!/usr/bin/ruby
a = [1,2,3,4,5]
b = a.collect{|x| 10*x}
puts b
This will produce the following results: