[#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: ostruct.rb patch

From: "Christoph" <chr_news@...>
Date: 2003-09-24 05:12:02 UTC
List: ruby-core #1561
"Nathaniel Talbott" wrote:

...
> +  def hash
> +    @table.keys.hash ^ @table.values.hash
> +  end

This hash function depends on the order of @table.keys resp. 
@table.value.  My guess that this probably not what you want.

Here is an counter example on my machine: (I used to able to 
produce a counter exampe with two elements only but it does 
not work with 1.8)
---
class A
  def initialize(x)
    @to_s = x
  end
  def to_s
    @to_s
  end
  alias inspect to_s 

  def self.find
    e,o,i,u = ['e','o','i','u'].collect { |s| A.new(s) }
    loop do
      l = {u => i , e => o,  o => e, i=>u }
      r = {i => u,  o => e,  e => o, u => i }
      return l,r if l.keys != r.keys
      e,o = A.new('e'),A.new('o')
    end
  end
end

l,r = A.find

puts l == r

p l
p r  
---
---
true
{o=>e, e=>o, u=>i, i=>u}
{o=>e, u=>i, e=>o, i=>u}
---


The upshot is:  Use something along the lines of 

def hash
    @table.inspect(0) {|hsh,pair|  hsh + pair[0]^(pair[1]<< 2) }
end


/Christoph 

In This Thread