Loops and Iterators in Ruby
while and for exist, but idiomatic Ruby reaches for times, each, and other iterator methods instead.
2 min read
Ruby has traditional loops, but you'll see them far less often than in other languages — Ruby's collections and integers come with built-in iterator methods that read more clearly than a manual loop.
while and until
count = 0
while count < 5
puts count
count += 1
end
count = 5
until count == 0
puts count
count -= 1
enduntil condition is while !condition — the same relationship unless has to if. Both exist and are used, but mostly for genuinely open-ended loops where you don't know the iteration count in advance (waiting on external state, reading until end-of-input).
for loops are rare
for i in 1..5
puts i
endThis works, but idiomatic Ruby almost never writes it this way — for doesn't create its own scope (the loop variable leaks out afterward), and each reads more clearly for the same job:
(1..5).each { |i| puts i }times, upto, downto, step
Integers themselves know how to iterate:
5.times { |i| puts i } # 0, 1, 2, 3, 4
1.upto(5) { |i| puts i } # 1, 2, 3, 4, 5
5.downto(1) { |i| puts i } # 5, 4, 3, 2, 1
1.step(10, 2) { |i| puts i } # 1, 3, 5, 7, 9Reaching for these instead of a manual for i in 0..n loop is one of the clearest tells of idiomatic Ruby — the intent ("do this 5 times," "count down from 5") is stated directly rather than reconstructed from loop mechanics.
each: the workhorse
each is how you'll iterate over arrays and hashes in almost all real code — full coverage is in the Collections section, but the shape is worth seeing now:
["a", "b", "c"].each { |letter| puts letter }
{ name: "Ada", role: :admin }.each do |key, value|
puts "#{key}: #{value}"
endNotice the block can be written as { ... } on one line or do ... end across multiple lines — they're functionally identical; the convention is {} for short one-liners and do...end for anything longer.
break, next, and redo
[1, 2, 3, 4, 5].each do |n|
next if n.even? # skip this iteration
break if n > 3 # exit the loop entirely
puts n
end
# prints: 1, 3next skips to the next iteration (like continue elsewhere), break exits the loop immediately. Both work inside while/until too, not just block-based iteration.
Loop as an expression
Because blocks can return a value, each and friends are often chained directly into further processing rather than used purely for side effects — a pattern the Enumerable Methods lesson covers in depth. For now, the takeaway is: reach for times/each/upto before reaching for a raw while loop, unless the loop genuinely has no fixed collection or count to iterate over.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.