How to Use the Until Loop in Ruby

09/25/2021

Contents

In this article, you will learn how to use the until loop in Ruby.

Using the until loop in Ruby

The until loop in Ruby is a type of loop that executes a block of code repeatedly until a certain condition becomes true.

Syntax

The syntax of the until loop is as follows:

until condition do
  # code to be executed
end

The condition is a Boolean expression that is evaluated before each iteration of the loop. If the condition is false, the block of code inside the loop is executed. This process continues until the condition becomes true.

Examples

Here’s an example of how to use the until loop in Ruby:

i = 0
until i > 5 do
  puts i
  i += 1
end

In this example, the until loop will execute the code block until the value of i becomes greater than 5. The output of this code will be:

0
1
2
3
4
5

Note that the until loop is similar to the while loop in Ruby, but the condition is evaluated in the opposite way. In other words, the while loop executes the code block while the condition is true, while the until loop executes the code block until the condition becomes true.

Here’s an example of using the until loop to implement a simple guessing game:

secret_number = 42
guess = nil

until guess == secret_number do
  print "Guess the secret number: "
  guess = gets.to_i
  if guess < secret_number
    puts "Too low, try again!"
  elsif guess > secret_number
    puts "Too high, try again!"
  else
    puts "Congratulations, you guessed the secret number!"
  end
end

In this example, the until loop is used to repeatedly ask the user for input until they guess the correct secret number. The loop continues until the guess variable is equal to the secret_number. If the guess is too low, the program prints “Too low, try again!” and asks the user for another guess. If the guess is too high, the program prints “Too high, try again!” and asks the user for another guess. If the guess is correct, the program prints “Congratulations, you guessed the secret number!” and exits the loop.