home PYTHONJAVA
 

Ruby iterator

In a nutshell: iterative refers to repeating the same thing, so an iterator is used to repeat the same thing multiple times.

Iterators are a supported method of collection. An object that stores a set of data members is called a collection. In Ruby, arrays (Arrays) and hashes (Hash) can be called collections.

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

Ruby each iterator

each iterator returns all elements of an array or hash.

Syntax

collection. Each do |variable| code end

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

Instance

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

The above example runs the output as:

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 after the other. The value is stored in the variable i and then displayed on the screen.

Ruby collect iterator

The

collect iterator returns all the elements of the collection.

Syntax

collection = Collection.collect
The

collect method does not need to be associated with a block at all times. The collect method returns the entire collection, whether it is an array or a hash.

Instance

Instance

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

The above example runs the output as:

1
2
3
4
5

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

When you want to do something with each value to get a new array, you usually use the collect method. For example, the following code will generate an array whose value is 10 times each value in a.

Instance

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

The above example runs the output as:

10
20
30
40
50





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.