Logical Operators
Learn about logical operators and how we use them in Ruby.
Logical operators are also, maybe more commonly, called boolean operators.
Boolean logic and its origin
The term “boolean” originates from the book The Mathematical Analysis of Logic, written by George Boole in . Boolean logic has been fundamental in the development of computers and programming because at their core, computers are all about processing whether or not there is a current flow: on vs. off (true vs. false).
Types of boolean operators
Feel free to look it up on your own time, but for now, we can simply focus on the three fundamental boolean operators and what they do: and
, or
, and not
.
The and operator
The and
operator always appears between two values (operands), and it returns true
if both values are true
. So, only the expression true
and true
is true
. All the following expressions, true and false
, false and true
, and false and false
, evaluate to false
.
If we think about this in the context of English sentences, then this will make a lot of sense. That is, I’ll have tomato soup at the restaurant if it’s vegan and they still have some.
The or operator
The or
operator, on the other hand, returns true
if at least one of the values is true
. So, it’s only false if both values are false
.
That’s why it’s logically correct to answer the question, “Would you like tea or coffee for breakfast?” with “Yes, please,” if you’d like either tea, or coffee, or both. We’d only say no if we’d like orange juice instead.
The not operator
The not
operator, unlike the and
and or
operators, operates on only one operand. The not
operator simply returns the negated, opposite value. For example, not true
returns false
, and not false
returns true
. Therefore, the following lines of code are the same:
puts "This is always: #{not false}"puts "This is always: #{not true}"
Operator precedence
Each of these three operators comes in two versions:
and
and&&
or
and||
not
and!
The difference between the two versions has to do with what’s called operator precedence.
Recall that 1 + 2 * 3
evaluates to 7
, not 9
, which we know through the order of operations. The multiplication (*
) operator is prioritized and therefore precedes the addition operator (+
). In other words, 1 + 2 * 3
is the same as 1 + (2 * 3)
, but it’s not the same as (1 + 2) * 3
.
In Ruby, the &&
, ||
, and !
operators are prioritized over and
, or
, and not
.
Note: The
and
operator is prioritized aboveor
, so an expression liketrue or true and false
is interpreted astrue or (true and false)
rather than(true or true) and false
, and it evaluates totrue
.
puts true or true and false