Ruby iterator
To put it simply: iterate means doing the same thing over and over again, sothe iterator is used to repeat the same thing many times.
Iterators are methods supported by collections. The object that stores a setof data members is called a collection. In Ruby, arrays (Array) and hashes can be called sets.
The iterator returns all the elements of the collection, one by one. Here wewill discuss two kinds of iterators each
and collect
.
Ruby each
iterator
The each
iterator returns all the elements of the array or hash.
Grammar
collection.eachdo\|variable\|codeend
Execute for each element in the collection code
. In this case, the collection can be an array or a hash.
Example
#!/usr/bin/rubyary=[1,2,3,4,5]ary.eachdo\|i\|putsiend
The output of the above instance is as follows:
1
2
3
4
5
each
iterator is always associated with a block. It returns each value of the array to the block, one by one. Values are stored in variables``i`` and then displayed on the screen.
Ruby collect
iterator
The collect
iterator returns all elements of the collection.
Grammar
collection=collection.collect
collect
method does not always need to be associated with a block. collect
method returns the entire collection, whether it is an array or a hash.
Example
Example
#!/usr/bin/rubya=[1,2,3,4,5]b=Array.newb=a.collect{ \|x\|x}putsb
The output of the above instance is as follows:
1
2
3
4
5
Note: collect
method is not the correct way to copy between arrays. Here’s another one called clone
method for copying one array to another
When you want to do something on each value to get a new array, you usually use the collect
method. For example, the following code generates an array whose value is 10 times that of each value.
Example
#!/usr/bin/rubya=[1,2,3,4,5]b=a.collect{\|x\|10*x}putsb
The output of the above instance is as follows:
10
20
30
40
50