Many of Ruby's control structures, such as
while, are standard fare and quite familiar to
programmers, while others, like
until, are not. Think of control structures, which contain
conditional statements, as lie detector tests. In every instance, when you use a control
structure with a conditional, you are asking if something is true or false. When you get the
desired answer—true or false depending on how you've designed your code—the code block
associated with the control is executed.
Two related structures,
ensure, which are used for exception handling, are not explained
here. They are discussed in Chapter 10.
This chapter introduces you to Ruby's control structures with plenty of examples, as
usual. We'll start out with the
if statement—one of the
most common structures in just about any programming language.
Let's start out really simple and build from there.
if 1 == 1 then print "True!" end
If it's true that 1 equals (
==) 1, which it does,
if statement returns
true, and the code block, consisting only of a
statement, by the way, could be typed out on one line.)
Now you'll create a variable and compare it with a number. If the variable and number are equal, the code is executed.
x = 256 if x == 256 puts "x equals 256" end # => x equals 256
Notice that we dropped
then from the
if statement. You don't have to use it in this instance. In addition, you don't have ...