0
0
Rubyprogramming~5 mins

Until loop in Ruby

Choose your learning style9 modes available
Introduction

An until loop repeats actions until a condition becomes true. It helps you do something over and over until you want to stop.

When you want to keep asking a user for input until they give a valid answer.
When you want to count up or down until a number reaches a limit.
When you want to repeat a task until a certain event happens.
When you want to wait for a condition to become true before moving on.
Syntax
Ruby
until condition
  # code to repeat
end

The loop runs while the condition is false.

Once the condition becomes true, the loop stops.

Examples
This prints numbers 1 to 5. The loop stops when count is greater than 5.
Ruby
count = 1
until count > 5
  puts count
  count += 1
end
This keeps asking for a password until the user types "secret".
Ruby
password = ""
until password == "secret"
  puts "Enter password:"
  password = gets.chomp
end
puts "Access granted!"
Sample Program

This program counts down from 10 to 1, then prints "Blast off!".

Ruby
number = 10
until number == 0
  puts "Countdown: #{number}"
  number -= 1
end
puts "Blast off!"
OutputSuccess
Important Notes

Be careful to change something inside the loop so the condition can become true, or the loop will run forever.

You can use until as a modifier after a single line, like puts count until count > 5.

Summary

Until loops repeat code while a condition is false.

They stop running when the condition becomes true.

Use them to repeat tasks until you want to stop.