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
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
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
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
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
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
This operator is mostly used for sorting functions.
Top comments (0)