Learn Ruby the Hard Way – Exercise 30 Else and If

Here is my work for Exercise 30.

Exercise 30 code
Exercise 30 code
Exercise 30 output
Exercise 30 output

Study Drills
1. Try to guess what elsif and else are doing.

First the condition for ‘if’ is evaluated, if it is true then the code block within is run. (None of the other code blocks in the if-elsif-else statement will be run.) If it is false, the next condition ‘elseif’ is evaluated, if that is true then the code block within that is run. If neither of the first two conditions are true, the block under ‘else’ is run.

2. Change the numbers of cars, people, and trucks and then trace through each if-statement to see what will be printed.
If we change cars = 10, people = 20, trucks = 30, then cars < people will be true, trucks > cars will be true, and people < trucks will be false. Therefore, line 8, line 14, and line 24 will be run and the strings printed to the screen.

We can change the variable values: cars = 10, people = 20, trucks = 30. When we run ex30.rb, we will get the following output:

confirmed!
Prediction confirmed!

3. Try some more complex boolean expressions like cars > people || trucks < cars.

Booleans and elsif
Booleans and elsif

I added the lines above to the end of the original exercise code. Since people > trucks is true, line 28 will be run. Since both cars > trucks and people > trucks are true, line 34 will be run.

The two lines are printed to the screen.
The two sentences (line 28 and 34) are printed to the screen.

4. Above each line write an English description of what the line does.

Commented Exercise 30 code
Commented Exercise 30 code 

Summary
This exercise uses if-elsif-statements to control what parts of our script will be run. If-elsif-statements allow us to check one by one if some conditions are true, and to have a default ‘else’ block for when none of the conditions are true.

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