Skip to main content

Ruby Iterators

Iterators are used to repeating instruction in multiple times. Which is, based on particular ranges, limit and object collection. There's many variant are available in Ruby programming.

Times Iterator

That is very simplest version of iterator. Which are execute instruction in fixed number steps.

number.times{|variable| 
  #instuction here
}

For example

5.times{|x| puts "#{x}"}
0
1
2
3
4

Variable are an optional parameter, When we are used this variable it will start 0 and increment one by one.

Collect Iterator

This are used to get element of particular collection like an array or hash. The speciality of this that are not modified actual collection. That's returning a new collection. And we can get modified version of actual collection.

#Array collection
data = [1,2,3,4,5]
#make new collection
new_data=data.collect{|old| old*10}

puts "#{data}"

puts "#{new_data}"
Collect example in ruby
[1, 2, 3, 4, 5]
[10, 20, 30, 40, 50]

Each Iterator

This iterator are gets element one by one in data collection.

collection.each do |variables|
   #logic here
end

Let see an example to display elements of an array.

[1,2,3,4].each do |element|
   puts element
end
1
2
3
4

When collection is combination of two values like key and value (hash element). Then we can use this way.

{1=>"One",2=>"Two",3=>"Three",4=>"Four"}.each do |key,value|
   puts value
end
One
Two
Three
Four

Upto Iterator

source.upto(destination) do |variable_name|

# logic here

end
10.upto(15) do |number|    
  puts number    
end
10
11
12
13
14
15

Downto Iterator

15.downto(10) do |number|    
  puts number    
end  
15
14
13
12
11
10

Step Iterator

This are provide some interval of given range.

(1..15).step(3) do |number|
  puts number
end
1
4
7
10
13

Each_Line Iterator

data ="Welcome To\nRuby\nProgramming"

data.each_line do|part|
  puts part
end
Welcome To
Ruby
Programming

note that \n is a new line character





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment