Comparison Operators

Learn about Ruby’s comparison operators.

In order to compare things, Ruby has a bunch of comparison operators.

The == operator

The == operator returns true if both objects are considered the same.

For example, 1 == 1 * 1 returns true because the numbers on both sides represent the same value. The expression "A" == "A" also returns true because both strings have the same value.

Two arrays are equivalent when they contain the same elements, in the same order. For example, [1, 2] == [1, 2] returns true, but [1, 2] == [2, 3] and [1, 2] == [2, 1] both return false.

What does the word “equivalent” mean?

Note that we say equivalent ( or considered the same) because the two objects technically don’t have to be the same objects, and they’re often not in our examples. For example, while evaluating the expression "A" == "A", Ruby creates two different string objects that both contain a single character, A.

In practice, this is almost always what we want. In the rare case when we actually need to check if two objects are the same, we use the equal? method, like below:

Press + to interact
puts "A".equal?("A")
letter="A"
puts letter.equal?(letter)

Other comparison operators

Other comparison operators are less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=). They also work on numbers and strings, exactly as we’d expect them to. Try a few combinations on numbers and strings.

Comparison operators are most often used with conditional statements to formulate conditions in if statements. We’ll learn more about these later, but here’s a quick look:

Press + to interact
number = 20
puts "#{number} is greater than 10." if number > 10

The <==> operator

The strangest operator in Ruby is <=> because it’s called the spaceship operator. It’s rarely used, but it’s useful for custom sorting.