Ruby iterator
In simple terms: Iteration (iterate) refers to repeat the same thing, so the iterator (iterator) that is used to repeat the same thing many times.
Iterator is acollectionof methods supported. Storing a set of data objects called members of the collection. In Ruby, arrays (Array) and hash (Hash) can be called a collection.
Iterator returns all elements of the collection, one by one. Here we will discuss twoiterators,each andcollect.
Rubyeach iterator
each iteration returns all the elements of an array or hash.
grammar
collection.each do |variable| code end
Codeexecution issetfor each element. Here, the set can be an array or hash.
Examples
#!/usr/bin/ruby ary = [1,2,3,4,5] ary.each do |i| puts i end
Run the above example output is:
1 2 3 4 5
eachiteration is always associated with a block. It returns an array of values to each block, one after another. Value is stored in the variablei, and then displayed on the screen.
Rubycollect iterator
collectiterator returns all elements of the collection.
grammar
collection = collection.collect
collectmethod need not always be associated with a block.collectmethod returns the entire collection, whether it is an array or hash.
Examples
#!/usr/bin/ruby a = [1,2,3,4,5] b = Array.new b = a.collect{ |x|x } puts b
Run the above example output is:
1 2 3 4 5
Note: collect method is not the right way to conduct inter-array replication.There is another calledclonemethod for copying an array to another array.
When you want to do something in order to obtain a value for each new array, you typically use the collect method. For example, the following code will generate an array whose value is a 10-fold for each value.
#!/usr/bin/ruby a = [1,2,3,4,5] b = a.collect{|x| 10*x} puts b
Run the above example output is:
10 20 30 40 50