Iterators in Ruby | Learning Hub

Iterators in Ruby | Learning Hub

There are different kinds of iterators provided by ruby a few of them are

Each Iterator

The each iterator is used to iterate through the elements of the array.

arr = [1, 2, 3, 4, 5]
arr.each { |a| print a -= 10, " " }
# prints: -9 -8 -7 -6 -5

The reverse each iterator, iterates through the list in reverse order.

words = %w[first second third fourth fifth sixth]
str = ""
words.reverse_each { |word| str += "#{word} " }
p str #=> "sixth fifth fourth third second first "

each_with_indexiterate over the elements in the array along with index.

arr = [1, 2, 3, 4, 5]
arr.each_with_index { |val,index| puts "index: #{index},value:#{val}"}
#output
index:0,value:1
index:1,value:2
index:2,value:3
index:3,value:4
index:4,value:5

Each Iterator can also be used with Hashes

h = { "a" => 100, "b" => 200 }
h.each {|key, value| puts "#{key} is #{value}" }
#output
a is 100
b is 200

h.each_key {|key| puts key }
#output
a
b

h.each_value {|value| puts value }
#output
100
200

Times Iterator

This iterator is used to iterate through the array from 0 to n-1 index positio

5.times do |i|
print i, " "
end
#OUTPUT
#=> 0 1 2 3 4

Upto and Downto Iterators

This iterator is used to iterate from value of n to the limit(including limit)

5.upto(10) { |i| print i, " " }
#=> 5 6 7 8 9 10

This iterator is used to iterate decreasing values from n to the limit(including limit)

5.downto(1) { |n| print n, ".. " }
#=> "5.. 4.. 3.. 2.. 1..

Step Iterator

The step iterator invokes a block which increments by the value of step with each iteration till the condition mentioned becomes false.

1.step(10, 2) { |i| print i, " " }
#output
1 3 5 7 9 => 1

Math::E.step(Math::PI, 0.2) { |f| print f, " " }
#output
2.718281828459045 2.9182818284590453 3.118281828459045 => 2.718281828459045

Each_Line Iterator

Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split into paragraphs delimited by multiple successive newlines.

print "Example one\n"
"hello\nworld".each_line {|s| p s}
print "Example two\n"
"hello\nworld".each_line('l') {|s| p s}
print "Example three\n"
"hello\n\n\nworld".each_line('') {|s| p s}
#OUTPUT
Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"