Ruby Iterators

Simply put: iteration means doing the same thing repeatedly, so an iterator is used to repeat the same thing multiple times.

Iterators arecollectionssupported methods. Objects that store a group of data members are called collections. In Ruby, arrays and hashes can be called collections.

Iterators return all elements of a collection, one after another. Here we will discuss two iterators,eachandcollect。

Ruby eachIterators

The each iterator returns all elements of an array or a hash.

Syntax

collection.each do |variable| code end

iscollectioneach element in the collection executescode. Here, the collection can be an array or a hash.

Examples

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

Try it »

The output of the above example is:

1
2
3
4
5

eachThe 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 the variableiand then displayed on the screen.

Ruby collectIterators

collectThe iterator returns all elements of a collection.

Syntax

collection = collection.collect

collectThe method does not always need to be associated with a block.collectThe method returns the entire collection, whether it is an array or a hash.

Examples

Examples

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

Try it »

The output of the above example is:

1
2
3
4
5

Note:collectThe method is not the correct way to copy between arrays. There is another method calledclone, which is used to copy one 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 generates an array whose values are 10 times each value in a.

Examples

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

Try it »

The output of the above example is:

10
20
30
40
50
Other Extensions