Ruby iterator
Simply put: iteration (iterate) refers to doing the same thing repeatedly, so an iterator (iterator) is used to repeat the same thing multiple times.
Iterator is a method supported by collection. An object that stores a set of data members is called a collection. In Ruby, arrays and hashes can be called sets.
The iterator returns all elements of the collection, one after the other. Here we will discuss two types of iterators, each and collect.
Ruby each Iterator
each Iterator returns all elements of an array or hash.
Syntax
collection.each do |variable| code end
Perform 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
The output result of the above example is:
1 2 3 4 5
each The iterator is always associated with one Block association. 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
collect Iterator returns all elements of the collection.
Syntax
collection = collection.collect
collect Methods need not always be associated with a block. collect method returns the entire collection, whether it is an array or a hash.
Example
#!/usr/bin/ruby a = [1,2,3,4,5] b = Array.new b = a.collect{ |x|x } puts b
The output result of the above example is:
1 2 3 4 5
Note:collect method is not the correct way to copy between arrays. There is another method called clone that copies one array to another.
You usually use the collect method when you want to do some operation on each value in order to get a new array. For example, the following code generates an array whose values are 10 times each value in a.
#!/usr/bin/ruby a = [1,2,3,4,5] b = a.collect{|x| 10*x} puts b
The output result of the above example is:
10 20 30 40 50