O'Reilly logo

The Ruby Programming Language by Yukihiro Matsumoto, David Flanagan

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

Chapter 5. Statements and Control Structures

image with no caption

Consider the following Ruby program. It adds two numbers passed to it on the command line and prints the sum:

x = ARGV[0].to_f  # Convert first argument to a number
y = ARGV[1].to_f  # Convert second argument to a number
sum = x + y       # Add the arguments
puts sum          # Print the sum

This is a simple program that consists primarily of variable assignment and method invocations. What makes it particularly simple is its purely sequential execution. The four lines of code are executed one after the other without branching or repetition. It is a rare program that can be this simple. This chapter introduces Ruby’s control structures, which alter the sequential execution, or flow-of-control, of a program. We cover:

  • Conditionals

  • Loops

  • Iterators and blocks

  • Flow-altering statements like return and break

  • Exceptions

  • The special-case BEGIN and END statements

  • The esoteric control structures known as fibers and continuations

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