Exercise 29: What If

Here is the next script of Ruby you will enter, which introduces you to the if-statement. Type this in, make it run exactly right, and then we'll see if your practice has paid off.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
people = 20
cats = 30
dogs = 15


if people < cats
  puts "Too many cats! The world is doomed!"
end

if people > cats
  puts "Not many cats! The world is saved!"
end

if people < dogs
  puts "The world is drooled on!"
end

if people > dogs
  puts "The world is dry!"
end


dogs += 5

if people >= dogs
  puts "People are greater than or equal to dogs."
end

if people <= dogs
  puts "People are less than or equal to dogs."
end


if people == dogs
  puts "People are dogs."
end

What You Should See

$ ruby ex29.rb
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.

Study Drills

In this Study Drill, try to guess what you think the if-statement is and what it does. Try to answer these questions in your own words before moving on to the next exercise:

  1. What do you think the if does to the code under it?
  2. Why does the code under the if need to be indented two spaces?
  3. What happens if it isn't indented?
  4. Can you put other boolean expressions from Exercise 27 in the if-statement? Try it.
  5. What happens if you change the initial values for people, cats, and dogs?

Common Student Questions

What does += mean?
The code x += 1 is the same as doing x = x + 1 but involves less typing. You can call this the "increment by" operator. The same goes for -= and many other expressions you'll learn later.

Buy DRM-Free

When you buy directly from the author, Zed A. Shaw, you'll get a professional quality PDF and hours of HD Video, all DRM-free and yours to download.

$29.99

Buy Directly From The Author

Or, you can read Learn Ruby the Hard Way for free right here, video lectures not included.