Search code examples
ruby

What is the effect of hash and eq implementation in Ruby


class A
  def hash
    12
  end

  def ==(other)
    true
  end
end

x = {}
a = A.new
b = A.new
x[a] = "Hello"
x[b] = "World"
puts x

This is printing:
{#<A:0x000055d1f3985c68>=>"Hello", #<A:0x000055d1f3985830>=>"World"}

I expected replacement, not happening, why?


Solution

  • Two objects are treated as the same hash key when their hash value is identical and the two objects are eql? to each other.

    http://www.ruby-doc.com/3.3.0/Hash.html#class-Hash-label-Hash+Key+Equivalence

    You have to define eql? instead of ==:

    class A
      def hash
        1
      end
    
      def eql? other
        true
      end
    end
    
    x = {}
    a = A.new 
    b = A.new
    
    x[a] = "Hello"
    x[b] = "World"
    
    p x
    
    #=> {#<A:0x00007fce035af608>=>"World"}