while and until
while repeats as long as a condition is true, and until repeats as long as it is false. It is like stirring until the soup is hot versus stirring while it is still cold.
In this page:
Syntax
while condition
# body
end
until condition
# body
end
while and until
while condition repeats its block as long as the condition is truthy, checked before each iteration. until condition is the inverse, repeating as long as the condition is falsy.
Both also support a trailing modifier form for a single statement, like i += 1 while i < 10.
Note:
until often reads more naturally than while !condition for conditions phrased as a stopping point.Example: while and until
count = 1
while count <= 3
puts "While count: #{count}"
count += 1
end
count = 1
until count > 3
puts "Until count: #{count}"
count += 1
end
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting to update the counter, so
while count <= 3runs forever. - Confusing
untilwithwhile, whenuntilruns while the condition is false. - Using
whilewheneachortimesis simpler and cannot loop forever.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: