Loops: while and until
Prerequisites: Conditionals
A loop repeats code. A while loop keeps going as long as its
condition is true.
Real-world analogy: "While the kettle isn't boiling, keep waiting."
Syntax
while condition
# repeated code
end
Example
count = 1
while count <= 3
puts "Count: #{count}"
count += 1
end
puts "Done"
Expected output
Count: 1
Count: 2
Count: 3
Done
Each pass checks count <= 3. After the third pass, count becomes
4, the condition is false, and the loop ends.
until is the opposite — it loops while the condition is false:
balance = 0
balance += 40 until balance >= 100
puts balance
120
loop do ... end repeats forever until you stop it with break (see
the break and next lesson). It's the clearest way to write "keep asking
until the input is valid".
In everyday Ruby, while loops are less common than you might expect —
iterators like times and each (next lesson) usually say the same
thing more clearly.
Common mistakes
- Forgetting to change the variable in the condition. Without
count += 1, the loop never ends — press Ctrl + C to stop it.
Practice
Use a while loop to print the numbers 10, 8, 6, 4, 2.
Show solution
n = 10
while n > 0
puts n
n -= 2
end