Ruby Tutorial Ruby References

Ruby - Until Loop



The Until Loop

Until loop allows a set of statements to be executed repeatedly as long as a specified condition is false. The program exits from the until loop when the given condition becomes true. The syntax for using until statement is given below:

Syntax

until condition [do]
  statements
end

In below mentioned example, program uses until loop to sum all integers from 1 to 5.

i = 1
sum = 0

until i == 6 do
  sum = sum + i
  i = i + 1
end

puts sum

The output of the above code will be:

15

until modifier

It keeps on executing the code if the until condition is false. If the code contains multiple lines, it can be enclosed within begin and end statements.

Syntax

#single line statement
statement while condition

#multi-line statements
begin
  statements 
end while condition

In the example below, the program prints the variable i until its value becomes 6.

i = 1

begin
  puts "i = #{i}"
  i = i + 1
end until i == 6

The output of the above code will be:

i = 1
i = 2
i = 3
i = 4
i = 5