The
redo
statement causes a loop to repeat the current
iteration. Sometimes, though, you need to wind the loop right back to
the very beginning. The
retry
statement is just the
ticket.
retry
restarts any kind of iterator loop.
for i in 1..100
print "Now at #{i}. Restart? "
retry if gets =~ /^y/i
end
|
Running this interactively, you might see
Now at 1. Restart? n
Now at 2. Restart? y
Now at 1. Restart? n
. . .
|
retry
will reevaluate any arguments to the iterator before
restarting it. The online Ruby documentation has the following example
of a do-it-yourself
until loop.
def doUntil(cond)
yield
retry unless cond
end
i = 0
doUntil(i > 3) {
print i, " "
i += 1
}
|
produces: