May 12, 2021 Ruby
An iterator is a method supported by a collection. A n object that stores a set of data members is called a collection. In Ruby, arrays and hash can be called collections.
The iterator returns all elements of the collection, one after the other. Here we will discuss two iterators, each and collect.
The each iterator returns all elements of the array or hash.
collection.each do |variable| code end
Code is executed for each element in the collection. Here, the collection can be an array or a hash.
#!/usr/bin/ruby ary = [1,2,3,4,5] ary.each do |i| puts i endTry it out . . .
This results in the following:
1 2 3 4 5
The each iterator is always associated with a block. I t returns each value of the array to the block, one after the other. The value is stored in variable i and then displayed on the screen.
The collect iterator returns all elements of the collection.
collection = collection.collect
The collect method does not need to always be associated with a block. The collect method returns the entire collection, whether it is an array or a hash.
#!/usr/bin/ruby a = [1,2,3,4,5] b = Array.new b = a.collect{ |x|x } puts bTry it out . . .
This results in the following:
1 2 3 4 5
Note: The collect method is not the correct way to copy between arrays. Here's another method called clone, which copies one array from one array to another.
You typically use the collect method when you want to do something with each value to get a new array. For example, the following code generates an array whose value is 10 times that of each value in a.
#!/usr/bin/ruby a = [1,2,3,4,5] b = a.collect{|x| 10*x} puts bTry it out . . .
This results in the following:
10 20 30 40 50