Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

BasicObject#equal?

(untyped other) -> bool
equal?(other) → true or false
eql?(other) → true or false

Alias of #==

Returns whether self and other are the same object:

Example
object = Object.new
object == object     # => true
object == Object.new # => false

Here in class Object, ==, equal?, and eql? are the same method. A subclass may override == to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses as it is used to determine object identity (that is, a.equal?(b) if and only if a is the same object as b):

Example
obj = "a"
other = obj.dup

obj == other      #=> true
obj.equal? other  #=> false
obj.equal? obj    #=> true

The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For any pair of objects where eql? returns true, the hash value of both objects must be equal. So any subclass that overrides eql? should also override hash appropriately.

For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition by aliasing eql? to their overridden == method, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

Example
1 == 1.0     #=> true
1.eql? 1.0   #=> false
See also #== #__id__ #!= #instance_eval also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0