Consider the following Ruby program. It adds two numbers passed to it on the command line and prints the sum:
x = ARGV.to_f # Convert first argument to a number y = ARGV.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:
Iterators and blocks
Flow-altering statements like
The special-case BEGIN and END statements
The esoteric control structures known as fibers and continuations
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
nil, then the condition is satisfied.
Ruby has a rich vocabulary for expressing conditionals. The syntax choices are described in the subsections that ...