Ruby - Statement while Loops

Introduction

Ruby has a while loop:

while aCondition
   doSomething
end 

Or, here's another way to put it:

doSomething while aCondition

The syntax of these two examples is different, they perform the same function.

In the first example, the code between while and end executes just as long as the Boolean condition evaluates to true.

The keyword do may optionally be placed between the test condition and the code to be executed when these appear on separate lines.

The do keyword is obligatory when the test condition and the code to be executed appear on the same line.

while Modifiers

In the second version of the loop (doSomething while aCondition), the code to be executed precedes the test condition.

This syntax is called a while modifier.

When you want to execute several expressions using this syntax, you can put them between the begin and end keywords:

begin  
   doOne
   doTwo
end while aCondition

Here is an example showing the various alternative syntax:

Demo

$counter = 0  

def tired #   ww  w.  j a v a 2 s  .  c  o  m
    if $counter >= 8 then 
       $counter = 0 
      return false 
    else 
        $counter += 1 
        return true 
    end      
end 

def snore 
    puts('snore....') 
end 

def sleep 
    puts("z" * $counter )  
end 

while tired do sleep end    # a single-line while loop 

while tired                       # a multiline while loop 
    sleep 
end 

sleep while tired                 # single-line while modifier 

begin                             # multiline while modifier 
    sleep  
    snore 
end while tired

Result

Related Topic