Ruby Iterator
In simple terms: Iteration refers to repeating the same action, so an iterator is used to repeat the same action multiple times.
Iterators are methods supported by collections. An object that stores a group of data members is called a collection. In Ruby, arrays (Array) and hashes (Hash) can be referred to as collections.
Iterators return all elements of the collection, one by one. Here, we will discuss two iterators, each and collect.
Ruby each Iterator
The each iterator returns all elements of an array or hash.
Syntax
collection.each do |variable|
code
end
Executes code for each element in the collection. Here, the collection can be an array or a hash.
Example
#!/usr/bin/ruby
ary = [1,2,3,4,5]
ary.each do |i|
puts i
end
The output of the above example is:
1
2
3
4
5
The each iterator is always associated with a block. It returns each value of the array to the block, one by one. The value is stored in the variable i and then displayed on the screen.
Ruby collect Iterator
The collect iterator returns all elements of the collection.
Syntax
collection = collection.collect
The collect method does not always need to be associated with a block. The collect method returns the entire collection, whether it is an array or a hash.
Example
#!/usr/bin/ruby
a = [1,2,3,4,5]
b = Array.new
b = a.collect{ |x|x }
puts b
The output of the above example is:
1
2
3
4
5
Note: The collect method is not the correct way to copy arrays. There is another method called clone for copying an array to another array.
When you want to perform some operation on each value to get a new array, you typically use the collect method. For example, the following code generates an array whose values are ten times each value in a.
Example
#!/usr/bin/ruby
a = [1,2,3,4,5]
b = a.collect{|x| 10*x}
puts b
The output of the above example is:
10
20
30
40
50