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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.82.253