while Loops

Ruby has a few other loop constructs too. This is how to do a while loop:

while tired
   sleep
end

Or, here’s another way to put it:

sleep while tired

Even though the syntax of these two examples is different, they perform the same function. In the first example, the code between while and end (here a call to a method named sleep) executes just as long as the Boolean condition (which, in this case, is the value returned by a method called tired) evaluates to true. As in for loops, 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 (sleep while tired), the code to be executed (sleep) precedes the test condition (while tired). 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
   sleep
   snore
end while tired

Here is an example showing the various alternative syntaxes:

1loops.rb

$hours_asleep = 0

def tired
    if $hours_asleep >= 8 then
       $hours_asleep = 0
      return false
    else
        $hours_asleep += 1
        return true
    end
end

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

def sleep
    puts("z" * $hours_asleep )
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

The last example in the previous code (the multiline while modifier) needs close consideration because it introduces some important new behavior. When a block of code delimited by begin and end precedes the while test, that code always executes at least once. In the other types of while loop, the code may never execute at all if the Boolean condition initially evaluates to false.

Ensuring a while Loop Executes at Least Once

Usually a while loops executes zero or more times since the Boolean test is evaluated before the loop executes; if the test returns false at the outset, the code inside the loop never runs. However, when the while test follows a block of code enclosed between begin and end, the loop executes one or more times as the Boolean expression is evaluated after the code inside the loop executes.

These examples should help clarify:

2loops.rb

x = 100

    # The code in this loop never runs
while (x < 100) do puts('x < 100') end

    # The code in this loop never runs
puts('x < 100') while (x < 100)

    # But the code in loop runs once
begin puts('x < 100') end while (x < 100)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.89.18