[#1551] Hashes as keys — "Nathaniel Talbott" <nathaniel@...>

I was just playing around with Hash#hash and discovered that you can't use a

13 messages 2003/09/23

Re: Hashes as keys

From: Joel VanderWerf <vjoel@...>
Date: 2003-09-23 23:05:21 UTC
List: ruby-core #1555
Nathaniel Talbott wrote:

> The underlying question is, why do two Hashes with the same content have
> different hash values?:

I'd like to know, too. Maybe a hash is thought of as an object with 
attributes, rather than just a collection.

Since this issue comes up for some of my own classes, such as geometric 
objects that should hash the same when their parameters are the same, I 
sometimes use a mixin to make it easy to designate the content of 
objects and use that for hashing. I wouldn't suggest applying it to 
Hash, since it's so inefficient, but it is simple...

   module ContentEquality
     def hash
       content.hash
     end

     def eql?(other)
       content.eql? other.content
     end

     # in general you might not want this one...
     def ==(other)
       content == other.content
     end
   end

   class Point
     include ContentEquality
     attr_accessor :x, :y, :z

     def initialize x, y, z
       @x, @y, @z = x, y, z
     end

     def content
       [@x, @y, @z]
     end
   end

   p1 = Point.new 1,2,3
   p2 = Point.new 1,2,3

   h = {p1 => 1}
   p h[p2]     # 1
   p p1 == p2  # true


In This Thread