Menu
Coddy logo textTech

Until Loop

Part of the Fundamentals section of Coddy's Ruby journey — lesson 45 of 88.

The until loop is the opposite of the while loop. Instead of running while a condition is true, it runs until a condition becomes true. Think of it as "keep going until this happens."

count = 1
until count > 3
  puts count
  count += 1
end

This outputs 1, 2, 3. The loop continues as long as count > 3 is false. Once count becomes 4, the condition is true, and the loop stops.

Compare this to the equivalent while loop:

# These two loops do the same thing:
while count <= 3    # run while this is TRUE
until count > 3     # run until this is TRUE

The until loop can make your code more readable when you're waiting for something to happen. Here's a countdown example:

num = 5
until num == 0
  puts num
  num -= 1
end
puts "Liftoff!"

This counts down from 5 to 1, then prints "Liftoff!" when num reaches 0. Choose until when it makes your intent clearer, especially when you're waiting for a specific condition to occur.

challenge icon

Challenge

Easy

Read a number n from input. Use an until loop to print all numbers from 1 up to n, each on its own line. After reaching n, print Done! on a new line.

The loop should continue until the counter exceeds n.

The input will be a single integer representing the target number.

For example, if the input is 4, the output should be:

1
2
3
4
Done!

If the input is 6, the output should be:

1
2
3
4
5
6
Done!

Cheat sheet

The until loop runs until a condition becomes true (opposite of while):

count = 1
until count > 3
  puts count
  count += 1
end
# Outputs: 1, 2, 3

Comparison with while loop:

while count <= 3    # run while this is TRUE
until count > 3     # run until this is TRUE

Example countdown:

num = 5
until num == 0
  puts num
  num -= 1
end
puts "Liftoff!"

Try it yourself

# Read the target number
n = gets.to_i

# Initialize counter
counter = 1

# TODO: Write your code below
# Use an until loop to print numbers from 1 to n
# The loop should continue until counter exceeds n


# Print "Done!" after the loop
puts "Done!"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals