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:
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:
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:
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:
numbers = [4, 9, 15, 22, 30]
i = 0
first_big = loop do
break numbers[i] if numbers[i] > 10
i += 1
end
p first_big15
next: skip to the next round
next jumps to the next iteration, skipping the rest of the body:
i = 0
while i < 10
i += 1
next if i % 3 != 0
puts "#{i} is divisible by 3"
end3 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:
x = 1
x *= 2 while x < 100
p x
y = 50
y -= 7 until y < 0
p y128
-6
for … in
Ruby has a for loop, but you will rarely see it in real code:
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:
["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:
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, usearr.eachorarr.each_with_indexinstead — shorter and impossible to get off-by-one.
Test yourself
Which loop runs as long as its condition is false?
whileuntilloopfor
What does next do inside a loop?
- Exits the loop
- Skips the rest of the current iteration
- Restarts the loop from the beginning
- Pauses the program
How do you stop a loop do ... end?
- It stops after 100 rounds
- With
break - With
end - It cannot be stopped