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:
returnCauses a method to exit and return a value to its caller.
breakCauses a loop (or iterator) to exit.
nextCauses a loop (or iterator) to skip the rest of the current iteration and move on to the next iteration.
redoRestarts a loop or iterator from the beginning.
retryRestarts an iterator, reevaluating the entire expression. The
retrykeyword can also be used in exception handling, as we’ll see later in the chapter.throw/catchA very general control structure that is named like and works like an exception propagation and handling mechanism.
throwandcatchare not Ruby’s primary exception mechanism (that would beraiseandrescue, 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access