Brief description of the iterator in Ruby and brief description of the Ruby Generator
The iterator is a method supported by the set. Objects that store a group of data members are called collections. In Ruby, arrays and hashes can be called collections.
The iterator returns all elements of the set, one after another. Here we will discuss two types of iterators, each and collect.
Ruby each iterator
The each iterator returns all elements of an array or hash.
Syntax
collection.each do |variable| codeend
Executes code for each element in the set. Here, the set can be an array or a hash.
Instance
#!/usr/bin/rubyary = [1,2,3,4,5]ary.each do |i| puts iend
This produces the following results:
12345
The each 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 variable I and displayed on the screen.
Ruby collect iterator
The collect iterator returns all elements of the set.
Syntax
collection = collection.collect
The collect method does not always need to be associated with a block. The collect method returns the entire set, whether it is an array or a hash.
Instance
#!/usr/bin/rubya = [1,2,3,4,5]b = Array.newb = a.collectputs b
This produces the following results:
12345
Note: The collect method is not the correct method for copying between arrays. Here is another method called clone, used to copy an array to another array.
When you want to perform operations on each value to obtain 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 in.
#!/usr/bin/rubya = [1,2,3,4,5]b = a.collect{|x| 10*x}puts b
This produces the following results:
1020304050