← Back to Ruby Course | Chapter 6: Control Flow | Lesson 4 of 7

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:

  1. while and until
Syntax
ruby
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

markup
count = 1

while count <= 3
  puts "While count: #{count}"
  count += 1
end

count = 1
until count > 3
  puts "Until count: #{count}"
  count += 1
end
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
  1. Forgetting to update the counter, so while count <= 3 runs forever.
  2. Confusing until with while, when until runs while the condition is false.
  3. Using while when each or times is simpler and cannot loop forever.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.