Expand All

Booleans

George Boole was an English mathematician who specialized in logic, especially logic rules involving true and false. The Boolean datatype is named in his honor.

In code, as in life, we base a lot of decisions on whether something is true or false. "If it is raining, then I will bring an umbrella; otherwise I will wear sunglasses." In the conditionals section we'll make decisions. First we need to look at true and false.

Goals

  • Meet True and False

  • Compare numbers and strings

  • Evaluate 'and', 'or', and 'not' logic

  • Understand methods ending with question marks (predicates)

Step 1

Here are some expressions that return true or false:

Type this in irb:
15 < 5
15 > 5
15 >= 5
10 == 12

Step 2

Notice we use a double equals sign to check if things are equal. It's a common mistake to use a single equals sign.

Type this in irb:
a = 'apple'
b = 'banana'
a == b
puts a + b
a = b
puts a + b

Surprise!

Step 3

For 'not equals', try these:

Type this in irb:
a = 'apple'
b = 'banana'
a != b

The exclamation point means the opposite of

Type this in irb:
!true
!false
!(a == b)

In !(a == b), Ruby first evaluated a == b, then gave the opposite.

It also means not true . In conditionals, we'll see things like

    if not sunny
        puts "Bring an umbrella!"

We can also say

    if sunny == false
        puts "Bring an umbrella!"

but "if not sunny" is a little more natural sounding. It's also a little safer - that double equals is easy to mistype as a single equals.

Step 4

We can check more than one condition with and and or . && and || (two pipes) is another notation for and and or.

We do something like this when we Google for 'microsoft and cambridge and not seattle'

Type this in irb:
# First let's define variables:
yes = true
no = false
# Now experiment.  Boolean rule 1:  AND means everything must be true. 
# true and true are true
yes and yes
yes && yes
# true and false fail the test - AND means everything must be true
yes and no
no and yes
no and no
# Boolean rule 2: OR says at least one must be true. 
yes or no
yes || no
yes or yes

Step 5

By convention, methods in Ruby that return booleans end with a question mark.

Type this in irb:
'sandwich'.end_with?('h')
'sandwich'.end_with?('z')
[1,2,3].include?(2)
[1,2,3].include?(9)
'is my string'.empty?
''.empty?
'is this nil'.nil?
nil.nil?

Explanation

In code we ask a lot of questions. Boolean logic gives us tools to express the questions.

Further Reading

Some languages offer wiggle room about what evaluates to true or false. Ruby has very little. See What's Truthy and Falsey in Ruby? for a more detailed walkthrough of booleans.

Ruby documentation for true and false

Next Step: