Yesterday we focused on being able to determine if statements are True or False (otherwise known as “boolean logic”). The value of boolean logic, or the need to make a choice, comes into play when we start putting conditional branches into our programs. A conditional branch is where one set of code blocks are exercised and run if a condition meets a criteria. If it doesn’t, then it ignores that block of code.
Today we get to see the first conditional statement, and that’s the “if” statement. “if” gives us a way to exercise a block of code when the condition associated with the “if” statement is true. Should the statement be false, then the code isn’t executed. Simple as that.
So here’s the example we’re given to work with:
And here’s what I did with it.
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.
In this extra credit, 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 onto the next exercise:
1. What do you think the if does to the code under it?
[ The if statement, as explained in my description above, is evaluating the statement associated with it and as it is currently written, testing to see if it is true. If it is true, then it executes the code that is indented within the if statement and then exits the if statement (that’s what the “end” represents). If the statement is fale, then the if statement does nothing, it passes control to the next line of code. ]
2. Can you put other boolean expressions from Ex. 27 in the if-statement? Try it.
[ Yes, any boolean expression can be used. For example, we could say, instead of “people < cats”, we could also say “not(people > cats)” or any of the other examples reworded for the program. ]
3. What happens if you change the initial variables for people, cats, and dogs?
[ Since each of the answers has to do with the equality or inequality of any of the variables, changing the values of one of them could result in different if statements being run and, subsequently, different test appearing in the program when it is run. ]
This is the beginning of “choice” in our programs, so to speak. the if-statement lets us run certain steps when the condition is true, and not run certain steps when the condition is not true. The if-statement is also our first “testing” statement. Up until now, our programs just did what we directed them to and the programs executed every line one after the other. With the if-statement, we’re testing to make sure the parameters are right to run a statement. If they aren’t we don’t. Fairly basic, but pretty powerful, too :).