tomaszbak
tomaszbak

Reputation: 8287

How to overwrite ruby Hash#[] key compare?

How to overwrite ruby Hash#[] key compare?

class FooBar
  def uid
    "123"  
  end
  alias_method :to_s, :uid

  def ==(other)
    self.uid == other.uid
  end
  alias_method :eql?, :==
end

class Foo < FooBar
end

class Bar < FooBar
end

Foo.new == Bar.new # returns true
Hash[[Foo.new,"succcess"]][Bar.new] # should return "succcess"
Hash[[Foo.new,"succcess"]].has_key? Bar.new # should return true

Upvotes: 0

Views: 209

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29419

You were close. You also needed to redefine hash. And you had an extra pair of brackets in your Hash creation. The following works:

class FooBar
  def uid
    "123"  
  end
  alias_method :to_s, :uid

  def ==(other)
    self.uid == other.uid
  end
  alias_method :eql?, :==

  def hash
    uid.hash
  end

end

class Foo < FooBar
end

class Bar < FooBar
end

Foo.new == Bar.new # returns true
Hash[Foo.new,"succcess"][Bar.new] # returns "succcess"
Hash[Foo.new,"succcess"].has_key? Bar.new # returns true

See Which equality test does Ruby's Hash use when comparing keys? for additional discussion.

Upvotes: 3

Related Questions