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 18471847. 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:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy