Welcome to Findnerd. Today we are going to discuss iterators in Ruby. Iterators are similar to loops but in iterators we know the beginning and end of the process. Please have a look.
v=0
while v<=10
v+=1
puts v
end
In above code we have written the while loop. Now we are going to write the same code using times iterator. Please have a look.
10.times do
puts 'Findnerd'
end
Above code will print the string Findnerd ten times. We can say, iterators make the code shorter and easy to manage. There are other iterators as well. Please have a look.
1.upto(10) { puts 'Findnerd' }
10.downto(1) { puts 'Findnerd' }
(1..10).each { puts 'Findnerd' }
In above code upto, downTo and each will print the string ten times but they are working in different ways. You can use these iterators in other ways.
1.upto(10) do |a|
puts 'Demo upto' + to_s(a)
end
employees = ['usa','heema','hema']
employees.each do |emp|
puts 'Name:' + emp
end
for emp in employees
puts 'Name' + emp.capitalize
end
In above code we have used three different iterators such as upto, each and for. In upto iterator we are using local variable which will be increased as iteration runs. In each and for iterator we are printing employees name.
There are other iterators as well in ruby so we are going to list them all. Please have a look.
A) Integer/floats : times, upto, downto, step
B) String: each, each_line, each_byte
C) Array: each, each_index, each_with_index
D) Range : each, step
E) Hash: each, each_key, each_value, each_pair
Thank you for being with us!
0 Comment(s)