Overriding hash function

suggest change

Ruby hashes use hash and eql? to choose a bucket and to compare keys. The default Object#hash is based on object identity, not on the object's fields. Override hash and eql? together.

If a.hash == b.hash, the two objects land in the same bucket, and they count as the same key when a.eql?(b) is true. If eql? says they are equal, they must return the same hash value. Otherwise a hash can hold what look like duplicate keys. A hash that always returns the same number puts every object in one bucket, and lookup becomes a linear eql? scan.

In the example below only the instance of class A is stored as a key, as it was added first:

class A
  def initialize(hash_value)
    @hash_value = hash_value
  end
  def hash
    @hash_value # Return the value given externally
  end
  def eql?(b)
    self.hash == b.hash
  end
end

class B < A
end

a = A.new(1)
b = B.new(1)

h = {}
h[a] = 1
h[b] = 2

raise "error" unless h.size == 1
raise "error" unless h.include? b
raise "error" unless h.include? a

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents