Ruby - Statement until Loops

Introduction

A while loops executes zero or more times since the Boolean test is evaluated before the loop executes.

If the test returns false at the outset, the code inside the loop never runs.

However, when the while test follows a block of code enclosed between begin and end, the loop executes one or more times as the Boolean expression is evaluated after the code inside the loop executes.

Demo

x = 100 

# The code in this loop never runs 
while (x < 100) do puts('x < 100') end 

# The code in this loop never runs 
puts('x < 100') while (x < 100) 

# But the code in loop runs once 
begin puts('x < 100') end while (x < 100)

Result

until Loops

Ruby has an until loop, which can be thought of as a while not loop.

The test condition and the code to be executed can be placed on a single line or can be placed on separate lines.

The until modifier puts the code before the test condition and encloses the code between begin and end in order to ensure that the code block is run at least once.

Demo

i = 10 

until i == 10 do puts(i) end           # never executes 
# from   w w w .j a  v a2 s .  c  om
until i == 10                          # never executes 
    puts(i) 
    i += 1   
end 

puts(i) until i == 10                  # never executes 

begin                                  # executes once 
    puts(i) 
end until i == 10

Result

Related Topic