Ruby Tutorial Ruby Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Ruby - While Loop



A loop statement allows a program to execute a statement(s) multiple times which provides easier and flexible programming. Ruby has three loop statements:

The While Loop

While loop allows a set of statements to be executed repeatedly until a given condition is true. The While loop can be viewed as a repeating if statement. A while loop expression is separated from code by the reserved word do, a newline, or a semicolon.

Syntax

while condition [do]
  statements
end

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

i = 1
sum = 0

while i < 6 do
  sum = sum + i
  i = i + 1
end

puts sum  

The output of the above code will be:

15

while modifier

It keeps on executing the code if the while condition is true. 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 while its value is less than equal to 5.

i = 1

begin
  puts "i = #{i}" 
  i = i + 1
end while i <= 5

The output of the above code will be:

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

loop do

One of the simplest way to create a loop in Ruby is using the loop method. The loop method executes a block of code, which can be denoted either by using { ... } or do ... end. It executes the block of code again and again until a manually intervene with Ctrl + c or break statement condition is fulfilled.

Syntax

#using { ... }
loop {
  statements
}

#using do ... end
loop do
  statements
end

In the example below, the program prints "Hello World!". It will keep on printing it until manually intervened by pressing Ctrl + c.

loop do
  puts "Hello World!" 
end

The output of the above code will be:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
and so on...

To stop the loop, a break statement can be used. When the break condition is fulfilled, the program will get out of the loop. Consider the example below, where the program breaks the loop when the value of variable i becomes 5.

i = 0

loop do
  i = i + 1  
  puts "value of i = #{i}" 
  if i == 5
    break
  end
end 

The output of the above code will be:

value of i = 1
value of i = 2
value of i = 3
value of i = 4
value of i = 5

5