Ruby Iterators
each, times, upto, downto, step and each_with_index cover almost all loops. Ranges like 1..5 and 1...5 are inclusive and exclusive.
Example
5.times { |i| print i }
puts
1.upto(3) { |i| print i }
puts
10.step(1, -3) { |i| print i, " " }
puts
(1...4).each { |i| print i }
puts
%w[a b].each_with_index { |x, i| puts "#{i}#{x}" }Result
01234 123 10 7 4 1 123 0a 1b
Exercise
Count down.
3.(1) { }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.