Learn Ruby the Hard Way – Exercise 29 What If

Here is my work for Exercise 29.

Exercise 29 code
Exercise 29 code
Output for Exercise 29
Output for Exercise 29

Study Drills
1. What do you think the if does to the code under it?

The expression after the ‘ if ‘ is the condition. The condition is evaluated, if the condition is true then the enclosed code will be run. If the condition is false, then the code will not be run.

2. Why does the code under the if need to be indented two spaces?
The indentation is not required but makes your code easier to read. When you have more complex code, indenting makes it clear which code lines are enclosed in functions and if…end.

3. What happens if it isn’t indented?
The code will still run the same.

4. Can you put other boolean expressions from Exercise 27 in the if-statement? Try it.
Yes, any boolean expression can be used in the if-statement.

I added a true statement from Exercise 28: !(“testing” == “testing” && “Zed” == “Cool Guy”)
Note that what is inside the brackets evaluates to false, but the ! makes the whole statement evaluate to true. This means that the code inside our if-statement will be run.

I added a "true" condition from ex28.rb
I added a “true” condition from ex28.rb, if it is true, we will print the sentence to the screen.
Output code: the condition is true and the sentence is printed.
Output code: the condition is true and the sentence is printed.

5. What happens if you change the initial values for people, cats, and dogs?
Depending on what the initial values are, different lines will be printed. For example if we change the number of cats to 10, the conditions on line 9, 17, 23, 27, 31 will be true. The corresponding code inside those if-statements will be run.

Let’s change cats to 10 and run the file again.

Now there are not too many cats in the world.
Now there are not too many cats in the world.

What if we change cats to 10 and dogs to 30? Now there are the biggest number of dogs.

Summary
This exercise combines boolean expressions and if-statements to run certain parts of the code depending on how the expressions evaluate. If the condition of the if-statement is true, the enclosed code will run. If the condition is false, the code will not be run.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s