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

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

Conditionals

The most common control structure, in any programming language, is the conditional. This is a way of telling the computer to conditionally execute some code: to execute it only if some condition is satisfied. The condition is an expression—if it evaluates to any value other than false or nil, then the condition is satisfied.

Ruby has a rich vocabulary for expressing conditionals. The syntax choices are described in the subsections that ...

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