Don't tell anyone, but Ruby has pretty primitive built-in looping
constructs.
The
while
loop executes its body zero or more times as long as
its condition is true. For example, this common idiom reads until
the input is exhausted.
There's also a negated form that executes the body until the
condition becomes true.
until playList.duration > 60
playList.add(songList.pop)
end
|
As with
if
and
unless
, both of the loops can also be used
as statement modifiers.
a *= 2 while a < 100
a -= 10 until a < 100
|
On page 78 in the section on boolean
expressions,
we said that a range can be used as a kind of flip-flop, returning true
when some event happens and then staying true until a second event occurs.
This facility is normally used within loops. In the example that
follows, we read a text file containing the first ten ordinal numbers
(``first,'' ``second,'' and so on)
but only print the lines starting with the one that matches
``third'' and ending with the one that matches ``fifth.''
file = File.open("ordinal")
while file.gets
print if /third/ .. /fifth/
end
|
produces:
The elements of a range used in a boolean expression can themselves be
expressions. These are evaluated each time the overall boolean
expression is evaluated. For example, the following code uses the fact
that the variable
$.
contains the current input line number to
display line numbers one through three and those between a match of
/eig/
and
/nin/
.
file = File.open("ordinal")
while file.gets
print if ($. == 1) || /eig/ .. ($. == 3) || /nin/
end
|
produces:
first
second
third
eighth
ninth
|
There's one wrinkle when
while
and
until
are used as statement
modifiers. If the statement they are modifying is a
begin
/
end
block,
the code in the block will always execute
at least one time, regardless of the value of the boolean expression.
print "Hello\n" while false
begin
print "Goodbye\n"
end while false
|
produces: