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 The Execute for each element in the collection The output of the above instance is as follows: The The output of the above instance is as follows: Note: When you want to do something on each value to get a new array, you usually use the The output of the above instance is as follows: each and collect . 6.26.1. Ruby
each iterator # each iterator returns all the elements of the array or hash.Grammar #
collection.eachdo\|variable\|codeend
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
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. 6.26.2. Ruby
collect iterator # 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. 6.26.3. Example #
Example #
#!/usr/bin/rubya=[1,2,3,4,5]b=Array.newb=a.collect{ \|x\|x}putsb
1
2
3
4
5
collect method is not the correct way to copy between arrays. Here’s another one called clone method for copying one array to another 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
10
20
30
40
50