0
0
RubyHow-ToBeginner · 3 min read

How to Use Until Loop in Ruby: Syntax and Examples

In Ruby, the until loop runs code repeatedly until a condition becomes true. It is the opposite of a while loop, running as long as the condition is false. Use until condition do ... end to repeat code until the condition is met.
📐

Syntax

The until loop runs the code inside it repeatedly until the given condition becomes true. It checks the condition before each iteration.

  • until: keyword to start the loop
  • condition: a test that returns true or false
  • do ... end: block of code to repeat

The loop stops when the condition is true.

ruby
until condition do
  # code to repeat
end
💻

Example

This example counts from 1 to 5 using an until loop. It repeats the code until the number is greater than 5.

ruby
count = 1
until count > 5 do
  puts count
  count += 1
end
Output
1 2 3 4 5
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to change the variable inside the loop, causing an infinite loop.
  • Using until when the condition is already true, so the loop never runs.

Always ensure the condition will eventually become true inside the loop.

ruby
count = 1
# Wrong: infinite loop because count never changes
# until count > 5 do
#   puts count
# end

# Correct:
until count > 5 do
  puts count
  count += 1
end
Output
1 2 3 4 5
📊

Quick Reference

KeywordDescription
untilStarts the loop that runs until the condition is true
conditionThe test that stops the loop when true
do ... endBlock of code to repeat
breakOptional keyword to exit the loop early

Key Takeaways

The until loop runs as long as the condition is false and stops when it becomes true.
Always update variables inside the loop to avoid infinite loops.
Use until when you want to repeat code until a condition is met, opposite of while.
The syntax is: until condition do ... end.
You can use break to exit the loop early if needed.