On 2/6/07, Andre Nathan <andre / digirati.com.br> wrote:
> 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?

You probably want a set.

require "set"

class A
 attr_reader :x, :y, :z

 def initialize(x, y, z = rand)
   @x = x
   @y = y
   @z = z
 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
puts "a1.z: #{a1.z}"
a2 = A.new('foo', 'bar')  # say @z = 0.90 here
puts "a2.z: #{a2.z}"

s = Set.new [a1]
p s
s.add(a2)
p s
p s.include?(a2)
p s.find { |m| m.eql?(a2) }.z

# Make it nicer:
def s.[] (lookup)
  self.find {|elem| elem.eql?(lookup) }
end

p s[a2].z

# Hope that helps
# pth