Step 6: Comparison Operators


In programming, it’s important for us to be able to compare values. Ruby gives us a number of operators to do this, and you’ve already seen one: ==, the equality operator.

3 == 3
# => true
4 == 5
# => false
12 / 3 == 4
# => true

Expressions with comparison operators return true or false. And if you’re wondering why Ruby uses two equals signs for this rather than just one, it’s not to be overly complicated for no reason. The single equals sign operator is used in Ruby for something else you’ll learn soon.

The greater than and less than operators are obvious:

1 < 2
# => true
22 < 17
# => false
14 > 6
# => true
15 > 100
# => false

Greater than or equal and less than or equal operators are pretty easy too:

15 <= 15
# => true
-19 >= 4
# => false

The != operator is used to test if two things are not equal. It will always return the opposite of ==:

10 != 10
# => false
256 != 4
# => true