O'Reilly logo

The Ruby Programming Language by David Flanagan, Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 and catch are not Ruby’s primary exception mechanism (that would be raise and rescue, described later in this chapter). Instead, they are used as a kind of multilevel or labeled break.

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required