So at this stage of the game we're going to do some practice and focus on "boolean logic" (which is where we say a statement is true or false based on the criteria, and we nly really care about the truth or falseness of the statement.
In this exercise we focus on trying to figure out whether or not the statements we enter are true or false. IRB will be our truth telling oracle for this experiment, and we shall see if our instincts are correct to tell if an expresion is true or false.
The Statements:
These statements sart out simple and get more complex as we move along through the examples. Some of the answers are obvious, some take a little more thought.
When statements get to be a bit more complicated, Zed recommends the following approach.
- Find equality test (== or !=) and replace it with its truth.
- Find each and/or inside a parenthesis and solve those first.
- Find each not and invert it.
- Find any remaining and/or and solve it.
- When you are done you should have true or false.
What You Should See
After you have tried to guess at these, this is what your session with IRB might look like:
$ irb
ruby-1.9.2-p180 :001 > true and true
=> true
ruby-1.9.2-p180 :002 > 1 == 1 and 2 == 2
=> true
Extra Credit
There are a lot of operators in Ruby similar to != and ==. Try to find out as many "equality operators" as you can. They should be like: < or <=.
[
<= - less than or equal to
< > - not
>= - greater than or equal to
<=> - looks to be greater than, less than or equal to (an allcharacter match?)
== - equal to
=== - equal to
!= - not equal to
=~ - ???
!~ - ???
]
Write out the names of each of these equality operators. For example, I call != "not equal".
Play with IRB by typing out new boolean operators, and before you hit enter try to shout out what it is. Do not think about it, just the first thing that comes to mind. Write it down then hit enter, and keep track of how many you get right and wrong.
[
1 <= 1 or 2 != 1
true and 1 >= 1
false and 0 != 0
true or 1 <=> 1
"test" == "testing"
1 != 0 and 2 === 1
"test" != "testing"
"test" =~ 1
not (true and false)
not (1 !~ 1 and 0 !~ 1)
]
TESTHEAD's TAKEAWAYS:
So that was interesting! I have to admit that at first I was wondering what the deal was and why so many variations would be needed, but it makes sense, especially if you think about a search parameter or a database query, you want to return a particular value if the statement evaluates to true, and you want to return another one if a statement evaluates to false. A lot of these won't make sense immediately, and that's OK, just keep practicing with them and sure enough, you start to see why they evaluiate to true or false over time.
No comments:
Post a Comment