Ruby Language Reference

while statement

Syntax:

while (conditional is true)
  p 'do something'
end

In this form of while loop, conditional is executed before the code is executed.

Example:

i = 0
while i < 3
  p "The value of i is : #{i}"
  i += 1
end

This prints:

The value of i is : 0
The value of i is : 1
The value of i is : 2

Then the program terminates.

One line while loop in Ruby

i = 0

p "The value of i is : #{i} incrementing to : #{i += 1}"  while i < 3

The reserved word while is used as a statement modifier. This prints:

The value of i is : 0 incrementing to : 1
The value of i is : 1 incrementing to : 2
The value of i is : 2 incrementing to : 3

Then the program terminates. You can also have while of this form:

i = 0
begin
  p "The value of i is : #{i}"
  i += 1  
end while i < 3

This prints:

The value of i is : 0
The value of i is : 1
The value of i is : 2

Then the program terminates. In this case, the code is evaluated before the conditional is evaluated.


Sharing is Caring