Cover by Michael Fitzgerald

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required