Wednesday, November 30, 2011

Exercise 30: Else And If: Learn Ruby the Hard Way: Practicum

Yesterday we focused on the if-statement and how it will run certain blocks of code when the conditions are right, and ignore the block of code if the conditions are wrong.

The thing with the if-statement is that, by itself, it is limiting, and it is verbose. If we had to make an if statement for all possibilities, there would be a lot of if statements to traverse. Most of the time, we just want to have a particular condition be taken care of one way, another one taken care of another way, and then if those don't meet the criteria, then do a default action. The if-statement alone won't do that. You need something else to do that and it's called, conveniently enough, "else" :).

What You Should See

$ ruby ex30.rb
We should take the cars.
Maybe we could take the buses.
Alright, let's just take the buses.

Extra Credit

Try to guess what elsif and else are doing.

[ elsif is following a secondary branch, and is only followed if the first condition is false, and this second condition is true. If the first condition is false, and the second condition is also false, then it will run the else statement, which will be a default statement to run if the other if and elsif statements are not true. ]

Change the numbers of cars, people, and buses and then trace through each if-statement to see what will be printed.

Try some more complex boolean expressions like cars > people and buses < cars. Above each line write an English description of what the line does.


The ability to have alternate options and a default help to keep the number of branches to a manageable level. Instead of having lots of if statements that stand alone, collecting them together in an if, elsif and else form would help organize the statements into groups, and the default else statement handles all of the examples that don't match the key areas of interest. With this, we get the ability to really start to make choices and make our programs behave how we want them to.

No comments: