English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Ruby Iterators

In simple terms: iteration (iterate) refers to doing the same thing repeatedly, so the iterator (iterator) is used to do the same thing multiple times.

iterator iscollectionmethods supported. An object that stores a set of data members is called a collection. In Ruby, arrays (Array) and hashes (Hash) can be called collections.

The iterator returns all elements of the collection, one after another. Here we will discuss two types of iterators,each and collect.

Ruby each Iterators

The each iterator returns all elements of the array or hash.

Syntax

collection.each do |variable|
   code
end

forcollectionexecute for each element in code. Here, the collection can be an array or a hash.

Online Examples

#!/usr/bin/ruby
 
ary = [1,2,3,4,5]
ary.each do |i|
   puts i
end

The output of the above examples is as follows:

1
2
3
4
5

each The iterator is always associated with a block. It returns each value of the array to the block, one after another. The values are stored in the variable i It is then displayed on the screen.

Ruby collect Iterators

collect Iterators return 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, regardless of whether it is an array or a hash.

Online Examples

Online Examples

#!/usr/bin/ruby
 
a = [1,2,3,4,5]
b = Array.new
b = a.collect{ |x|x }
puts b

The output of the above examples is as follows:

1
2
3
4
5

Note:collect method is not the correct way to copy between arrays. There is another called clone method, used to copy an array to another array.

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 will generate an array whose values are the 10 times.

Online Examples

#!/usr/bin/ruby
 
a = [1,2,3,4,5]
b = a.collect{|x| 10*x}
puts b

The output of the above examples is as follows:

10
20
30
40
50