Ruby Iterators
Simply put: to iterate means to do the same thing repeatedly, so an iterator is used to repeat the same thing multiple times.
Iterators areUnionsupported methods. An object that stores a collection of data members is called a collection. In Ruby, arrays (Array) and hashes (Hash) can be called collections.
An iterator returns all elements of a 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
isUnionexecutes for each element in code. 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
Try it »
The above example produces the following output:
1
2
3
4
5
each An 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
collect The iterator returns all elements of the collection.
Syntax
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.
Example
Example
!/usr/bin/ruby
a
=
[
1
,
2
,
3
,
4
,
5
]
b
=
Array
.
new
b
=
a
.
collect
{ |
x
|
x
}
puts
b
Try it »
The above example produces the following output:
1
2
3
4
5
Note:collect method is not the correct way to copy between arrays. There is another method called clone for copying one array to another.
When you want to perform some operation on each value to obtain a new array, you usually use the collect method. For example, the following code generates an array whose values are 10 times each value in a.
Example
!/usr/bin/ruby
a
=
[
1
,
2
,
3
,
4
,
5
]
b
=
a
.
collect
{|
x
|
10
x
}
puts
b
Try it »
The above example produces the following output:
10
20
30
40
50