Equality in Ruby

188 views

What is the return value of the following Ruby code?

1.0.eql?(1)   # => false
1.0.equal?(1) # => false

1.0 == 1      # => ???

The correct answer is

true

false

nil

It raises ArgumentError

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

The provided Ruby code snippet demonstrates the different ways in which a floating-point number (1.0) and an integer (1) can be compared in Ruby using the eql?, equal?, and == methods.

Let's break down each line of the code and understand what is happening:

1.0.eql?(1) (hash key)

"The eql? method in Ruby compares objects using their Object#hash method.

In this specific example, 1.0.eql?(1) returns false because Float#eql? overrides Object#eql?, causing it to return true only if the second operand is a Float with the same value as self, and false otherwise.

1.0.equal?(1) (object identity)

The equal? method in Ruby checks whether two objects refer to the same object in memory (using Kernel#object_id).

The result is also false because 1.0 and 1 are different objects in memory.

They have different identities, even though their values might be considered equal in a loose sense.

1.0 == 1 (operands)

The == operator is used for loose equality checking. It compares the values of two objects without considering their types.

In this case, the result is true because the numeric values of 1.0 and 1 are the same, even though they are of different types.

Understanding these distinctions is crucial in Ruby to ensure that you are comparing objects in a way that aligns with your intended logic, considering both value and type or just the value.

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©