Altering Control Flow
In addition to conditionals, loops, and iterators, Ruby supports a number of statements that alter the flow-of-control in a Ruby program. These statements are:
return
Causes a method to exit and return a value to its caller.
break
Causes a loop (or iterator) to exit.
next
Causes a loop (or iterator) to skip the rest of the current iteration and move on to the next iteration.
redo
Restarts a loop or iterator from the beginning.
retry
Restarts an iterator, reevaluating the entire expression. The
retry
keyword can also be used in exception handling, as we’ll see later in the chapter.throw/catch
A very general control structure that is named like and works like an exception propagation and handling mechanism.
throw
andcatch
are not Ruby’s primary exception mechanism (that would beraise
andrescue
, described later in this chapter). Instead, they are used as a kind of multilevel or labeledbreak
.
The subsections that follow describe each of these statements in detail.
return
The return
statement causes
the enclosing method to return to its caller. If you know C, Java, or
a related language, you probably already have an intuitive
understanding of the return
statement. Don’t skip this section, however, because the behavior of
return
within a block may not be
intuitive to you.
return
may optionally be
followed by an expression, or a comma-separated list of expressions.
If there is no expression, then the return value of the method is
nil
. If there is one expression, then the value ...
Get The Ruby Programming Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.