Ruby Iterators
Simply put: iteration means doing the same thing repeatedly, so an iterator is used to repeat the same thing multiple times.
Iterators arecollectionssupported methods. Objects that store a group of data members are called collections. 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,eachandcollect。
Ruby eachIterators
The each iterator returns all elements of an array or a hash.
Syntax
iscollectioneach element in the collection executescode. Here, the collection can be an array or a hash.
The output of the above example is:
1 2 3 4 5
eachThe iterator is always associated with a block. It returns each value of the array to the block, one after another. The value is stored in the variableiand then displayed on the screen.
Ruby collectIterators
collectThe iterator returns all elements of a collection.
Syntax
collectThe method does not always need to be associated with a block.collectThe method returns the entire collection, whether it is an array or a hash.
Examples
The output of the above example is:
1 2 3 4 5
Note:collectThe method is not the correct way to copy between arrays. There is another method calledclone, which is used to copy one array to another array.
When you want to perform some operation on each value to obtain a new array, you usually use the collect method. For example, the following code generates an array whose values are 10 times each value in a.
The output of the above example is:
10 20 30 40 50Other Extensions