How to Use While Loop in Ruby: Syntax and Examples
In Ruby, a
while loop repeats a block of code as long as a given condition is true. You write it using while condition do ... end or simply while condition ... end. It is useful for running code multiple times until the condition becomes false.Syntax
The while loop runs the code inside it repeatedly as long as the condition is true.
- condition: A test that returns true or false.
- do ... end: The block of code to repeat. The
dokeyword is optional.
ruby
while condition do
# code to repeat
endExample
This example counts from 1 to 5 using a while loop and prints each number.
ruby
count = 1 while count <= 5 puts count count += 1 end
Output
1
2
3
4
5
Common Pitfalls
One common mistake is forgetting to change the condition inside the loop, which causes an infinite loop.
Also, using while with a condition that is false at the start means the loop never runs.
ruby
count = 1 while count <= 5 puts count # Missing count += 1 causes infinite loop end # Correct way: count = 1 while count <= 5 puts count count += 1 end
Quick Reference
- Use
whileto repeat code while a condition is true. - Remember to update variables inside the loop to avoid infinite loops.
- The
dokeyword is optional. - Use
breakto exit the loop early if needed.
Key Takeaways
Use
while to repeat code as long as a condition is true.Always update the condition inside the loop to avoid infinite loops.
The
do keyword is optional in while loops.Use
break to stop the loop before the condition becomes false.If the condition is false initially, the loop code will not run at all.