[#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: Eugene Scripnik <Eugene.Scripnik@...>
Date: 2003-09-24 07:32:50 UTC
List: ruby-core #1563
Nathaniel Talbott wrote:
> I was just playing around with Hash#hash and discovered that you can't use a
> Hash as a key in a hash:
> 
>   h = {{} => 'a'}
>   p h[{}]
> 
>   => nil
> 
> Is this intentional? Since hash overrides #==, I expected it to do the same
> with #hash, but it appears that it just uses Object#hash, which is different
> for every instance.
Implement #hash and #eql? methods in the way you think they should work 
and you'll get expected results:

$ cat myhash.rb
class MyHash < Hash
     def hash
         current = 17
         self.each do |k, v|
             current = current * 37 + k.hash
             current = current * 37 + v.hash
         end
         return current
     end

     def eql?( h )
         return false if self.keys.length != h.keys.length
         h.each do |k, v|
             return false unless self.has_key?( k ) and self[k] == v
         end
         return true
     end
end

h = {}

h1 = MyHash.new
h1[:key] = 'value'

h2 = MyHash.new
h2[:key] = 'value'

h[h1] = 'a'

puts h[h2]

-- 
Eugene Scripnik
IT Group
Software Architect
Tel./Fax +380 (372) 58-43-10
email: Eugene.Scripnik@itgrp.net
http://www.itgrp.net/


In This Thread