From: gga Date: 2007-02-08T11:35:11+09:00 Subject: Re: Fetching objects used as hash keys On 6 feb, 16:04, Andre Nathan wrote: > Hello > > I'm using objects which are instances of a class that has 3 instance > variables as hash keys, but I'm using the value of only two of those > instance variables for the hash calculation. It's something like this: > > class A > attr_reader :x, :y, :z > > def initialize(x, y) > @x = x > @y = y > @z = rand > end > > def hash > @x.hash ^ @y.hash > end > > def eql?(other) > @x == other.x and @y == other.y > end > end > > a1 = A.new('foo', 'bar') # say @z = 0.25 here > a2 = A.new('foo', 'bar') # say @z = 0.90 here > > h = {} > h[a1] = true > p h[a2] #=> true > Okay, your explanation does not make much sense. But... if @z is not needed and you want it to be returned as the hash value, why is it in the class? Make *that* the hash value, like: h = {} h[a1] = rand p h[a2] >> 0.25 should give you what you want. If you do want it in the class, then you don't need a hash. Just doing a1.z should give you back what you want. If you need it in both, pass it around when you create it, like: h = {} [ a1, a2 ]. each { |key| z = h[key] || rand h[key] = z key.z = z # make z attr_accessor, not attr_reader of course } Or did I miss something?