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:

Create a free account to access the full course.

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