Chapter 3. Conditional Love
Many of Ruby’s control structures, such as if
and
while
, are standard fare and quite familiar to
programmers, while others, like unless
and 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.
Tip
Two related structures, rescue
and 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.
The if Statement
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,
then the if
statement returns true
, and the code block, consisting only of a print
statement, will execute. (This if
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 ...
Get Learning Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.