Ruby While Loops
A while loop is a block of code that repeats while its test stays true. The loop stops when the test turns false.
While counts up
The count starts at 1. Each turn prints the count, then adds one to it.
count = 1
while count <= 3
puts count
count += 1
endUntil counts down
The count starts at 3. The until loop runs while the count is not yet 0.
count = 3
until count == 0
puts count
count -= 1
endA modifier while line
A modifier while line puts the test after one statement. The statement repeats while the test stays true.
count = 0
count += 1 while count < 3
puts countExample
count = 2
while count <= 8
puts count
count += 2
end
puts "Done"Key points
- A while loop checks its test before each turn.
- The body runs one full turn, then the test runs again.
- Use count += 1 to move a count up by one on each turn.
- Until is the mirror word for while.
- An until loop stops when its test turns true.
- A loop whose test never turns false never stops.
In this example, the count starts at 2. The test passes, so the loop prints 2 and adds 2 to the count. The turns print 4, 6, and 8 in the same way. The count then reaches 10 and the test turns false. The last line prints Done after the loop ends.
Note
A test in a while or until line needs no brackets around it.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
What must happen for a while loop to stop?