DEV Community

Cover image for Learning Ruby: check equality
Rossella Ferrandino
Rossella Ferrandino

Posted on

Learning Ruby: check equality

There are different ways to determine whether two values are the same in Ruby.

Equality operators: == and !=

The equals operator == will return true if the values compared are equal.

string_one = "Cookies"
string_two = "Cookies"

string_one == string_two   #Output: => true
string_one != string_two   #Output: => false
Enter fullscreen mode Exit fullscreen mode

When we compare numbers of different types (float and integer), the equals operator will return true if both have the same numeric value.

7 == 7.0   #Output: => true
Enter fullscreen mode Exit fullscreen mode

eql?

The eql? method checks both the value type and the exact value it holds. So an integer and a float that have the same numeric value will not be equal.

7.eql?(7.0)   #Output: => false
Enter fullscreen mode Exit fullscreen mode

equal?

The equal? method is the strictest form of comparison in Ruby. It checks whether both values are the exact same object in memory.

a = "Cookies"
b = "Cookies"

puts a.object_id #Output: => 47343105968220
puts b.object_id #Output: => 47343105968200

a.equal? b  # Output: => false
Enter fullscreen mode Exit fullscreen mode

Things are a bit different for numbers, because of the way computers store integers in memory. 7 will always point at the same object id, so if we assign the number 7 to two different variables and use the equal? method on those two variables, the result will be true.

a = 7
b = 7

puts a.object_id # Output: => 15
puts b.object_id # Output: => 15

puts a.equal?(b)  # Output: => true

Enter fullscreen mode Exit fullscreen mode

The spaceship operator <=>

Differently from the previous operators / methods, the spaceship operator does not return true or false, but it returns one of three numerical values.

  • -1 if the value on the left is less than the value on the right
  • 0 if the value on the left is equal to the value on the right
  • 1 if the value on the left is greater than the value on the right

7 <=> 8 # Output: => -1
7 <=> 7.0 # Output: => 0
7 <=> 7 # Output: => 0
7 <=> 1 # Output: => 1

Enter fullscreen mode Exit fullscreen mode

This operator is mostly used for sorting functions.

Top comments (0)