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
I did it this way because when I need to test the presence of an object
in the hash, the value of @z is not known (and doesn't matter). However,
once I know the object is there, I'd like to fetch it, and check the
value of @z of the object that was used as the hash key, that is, I'd
like to get "0.25" in the example above.
What I had to do was use a hash of hashes instead, so I currently I have
h = {}
x = 'foo'
h[x] = {
:y => 'bar'
:z => rand
}
So I'm guessing maybe a hash isn't the correct data structure to do what
I want here (i.e., fetch an object based on some of its attributes).
Anyone has suggestions on how I could implement that, if possible
keeping the efficiency of a hash access?
Thanks in advance,
Andre