Iterators are methods that are supported by collections. 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 the collection, one after the other. Here we'll discuss two kinds of iterators, each and collect.
Ruby each iterator
Each iterator returns all elements of an array or hash.
Grammar
Collection.each do |variable|
Code End
Executes code for each element in the collection. Here, the collection can be an array or a hash.
Instance
#!/usr/bin/ruby
ary = [1,2,3,4,5]
Ary.each do |i|
Puts I end
This will produce the following results:
Each iterator is always associated with a block. It returns each value of the array to the block, one after the other. The value is stored in the variable i and then displayed on the screen.
Ruby Collect iterator
The Collect iterator returns all the elements of the collection.
Grammar
Collection = Collection.collect
The Collect method does not need to always be associated with a block. The Collect method returns the entire collection, whether it is an array or a hash.
Instance
#!/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 Collect method is not the correct way to replicate between arrays. Here is another method called Clone, which is used to copy an array to another array.
When you want to do something with each value to get a new array, you typically use the Collect method. For example, the following code generates an array with a value of 10 times times each value in a.
#!/usr/bin/ruby
a = [1,2,3,4,5]
b = a.collect{|x| 10*x}
puts b
This will produce the following results: