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
endThis 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 TRUEThe 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
EasyRead 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, 3Comparison with while loop:
while count <= 3 # run while this is TRUE
until count > 3 # run until this is TRUEExample 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!"This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False