TExcelTAD
Home › Ruby › Ruby Loops

Ruby Loops

A loop repeats code. Ruby has classic loop keywords — while, until, loop and for — but idiomatic Ruby code uses them less often than other languages, because iterators like each and times (next lesson) cover most needs. You still need the keywords when you don't know in advance how many repetitions there will be.

while

while repeats as long as its condition is truthy:

ruby · try it yourself
countdown = 5
while countdown > 0
  print countdown, " "
  countdown -= 1
end
puts "Liftoff!"
5 4 3 2 1 Liftoff!

Make sure something inside the loop eventually makes the condition false — otherwise the loop runs forever.

until

until is the opposite: it repeats as long as its condition is false:

ruby · try it yourself
balance = 100
years = 0
until balance >= 150
  balance *= 1.1
  years += 1
end
puts "It takes #{years} years to reach #{balance.round(2)}"
It takes 5 years to reach 161.05

loop with break

loop repeats forever until you break out of it. This is the cleanest form when the exit condition is in the middle of the body:

ruby · try it yourself
n = 27
steps = 0
loop do
  break if n == 1
  n = n.even? ? n / 2 : 3 * n + 1
  steps += 1
end
puts "Collatz steps for 27: #{steps}"
Collatz steps for 27: 111

break can also carry a value, which becomes the value of the whole loop expression:

ruby · try it yourself
numbers = [4, 9, 15, 22, 30]
i = 0
first_big = loop do
  break numbers[i] if numbers[i] > 10
  i += 1
end
p first_big
15

next: skip to the next round

next jumps to the next iteration, skipping the rest of the body:

ruby · try it yourself
i = 0
while i < 10
  i += 1
  next if i % 3 != 0
  puts "#{i} is divisible by 3"
end
3 is divisible by 3
6 is divisible by 3
9 is divisible by 3

Modifier form

Like if, while and until can follow a single statement:

ruby · try it yourself
x = 1
x *= 2 while x < 100
p x

y = 50
y -= 7 until y < 0
p y
128
-6

for … in

Ruby has a for loop, but you will rarely see it in real code:

ruby · try it yourself
for fruit in ["fig", "plum"]
  puts fruit
end

for i in 1..3
  print i
end
puts
p i   # the loop variable still exists after the loop!
fig
plum
123
3

for is really a thin wrapper around each, and its variable "leaks" out of the loop. Rubyists prefer each, which keeps the variable inside the block:

ruby
["fig", "plum"].each { |fruit| puts fruit }
(1..3).each { |i| print i }

Nested loops

break only leaves the innermost loop. To exit several levels, wrap them in a method and return, or use catch/throw:

ruby · try it yourself
def find_pair(target)
  (1..9).each do |a|
    (a..9).each do |b|
      return [a, b] if a * b == target
    end
  end
  nil
end

p find_pair(24)
p find_pair(97)
[3, 8]
nil

Summary

Construct Runs while… Typical use
while cond cond is truthy Unknown number of repetitions
until cond cond is falsy "Keep going until something happens"
loop do … end forever, until break Exit condition in the middle
for x in coll items remain Rarely — prefer each
n.times, each, upto — Known collections or counts (next lesson)
Keyword Effect
break leave the loop (optionally with a value)
next skip to the next iteration
redo repeat the current iteration (rare)

Tip: If you find yourself writing i = 0; while i < arr.length; ...; i += 1; end, use arr.each or arr.each_with_index instead — shorter and impossible to get off-by-one.

Test yourself

Which loop runs as long as its condition is false?

  1. while
  2. until
  3. loop
  4. for

What does next do inside a loop?

  1. Exits the loop
  2. Skips the rest of the current iteration
  3. Restarts the loop from the beginning
  4. Pauses the program

How do you stop a loop do ... end?

  1. It stops after 100 rounds
  2. With break
  3. With end
  4. It cannot be stopped