AnyCompiler

Loops and Iterators

Ruby has while and until (until is simply while with the condition negated), both ordinary C-style loop keywords. It also has for, which iterates a range or collection. All three work, and all three are rare in real Ruby code — idiomatic Ruby almost always reaches for a method call with a block instead: n.times, array.each, range.each. This isn't a stylistic quirk; it's a direct consequence of lesson 5 — since collections and integers are already objects with iteration behavior built in as methods, writing a manual loop by hand is usually solving a problem Ruby already solved for you.

i = 0
while i < 3
  puts "while: #{i}"
  i += 1
end

3.times { |n| puts "times: #{n}" }
[10, 20, 30].each { |v| puts "each: #{v}" }
Output
while: 0
while: 1
while: 2
times: 0
times: 1
times: 2
each: 10
each: 20
each: 30
for i in 1..3
  puts "for: #{i}"
end

n = 5
n -= 1 until n == 0
puts "n is now #{n}"
Output
for: 1
for: 2
for: 3
n is now 0

n -= 1 until n == 0 reads almost like English: keep subtracting 1 from n until n equals 0. Next: arrays — Ruby's ordered, growable lists, and the methods built on top of them.

Practice exercise

Sum the numbers 1 through 10 using (1..10).each with a block, then print the sum.