Ruby While Loop

Ruby While Loop

The Ruby While loop statement syntax and example. The While loop executes ruby code while condition is true.

While loop syntax

while condition
	-- Ruby code 
end
--or
begin
	-- Ruby code 
end while condition

While loop example 1

$x = 1
while $x <= 3  do
   puts("While loop x = #$x" )
   $x +=1
end

Output

While loop x = 1

While loop x = 2

While loop x = 3

While loop example 2

$x = 1
begin
   puts("While loop x = #$x" )
   $x +=1
end while $x <= 3  

Output

While loop x = 1

While loop x = 2

While loop x = 3