Use of each and collect in Ruby for iteration, rubycollect
The iterator is nothing, but the set method is supported. Objects that store a group of data members are called collections. In Ruby, arrays and hashing can be called collections.
The iterator returns all elements of a set, one before and one after. We will discuss two iterators, each of which is collected here. Let's take a look at these details.
Ruby each iteration:
Each iterator returns all elements or hash of an array.
Syntax:
collection.each do |variable| codeend
Code executed by each element in the set. The collection may be an array or ruby hash.
Example:
#!/usr/bin/rubyary = [1,2,3,4,5]ary.each do |i| puts iend
The result is as follows:
12345
You are always associated with each iteration of the block. It returns each value of the array, one by one. The value is stored in variable I and displayed on the screen.
Ruby collect iteration:
The collected iterator returns all elements of a set.
Syntax:
collection = collection.collect
The collection method does not always require blocks. The collection method returns the entire set, whether it is an array or a hash.
For example:
#!/usr/bin/rubya = [1,2,3,4,5]b = Array.newb = a.collectputs b
This produces the following results:
12345
Note: The collection method is incorrect for copying between arrays. Another method is clone. Copy one array to another.
You usually use the collection method when you want to do something with each value to get a new array. For example, this code contains 10 times of each value and generates an array B.
#!/usr/bin/rubya = [1,2,3,4,5]b = a.collect{|x| 10*x}puts b
This produces the following results:
1020304050