Loops and Iterators
Idiomatic Ruby uses iterators instead of counters: each, times, upto and step. while and until also exist, and break and next control the loop.
Example
3.times { |i| puts "round #{i}" }
1.upto(3) { |i| print i, " " }
puts
(1..10).step(3) { |i| print i, " " }
puts
n = 3
while n > 0
n -= 1
end
%w[a b c].each_with_index { |l, i| puts "#{i}:#{l}" }Result
round 0 round 1 round 2 1 2 3 1 4 7 10 0:a 1:b 2:c
Exercise
Repeat 3 times.
3. { puts "hi" }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.