如何覆盖ruby哈希#[]键比较?

时间:2013-12-06 14:46:26

标签: ruby hash

如何覆盖ruby哈希#[]键比较?

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

1 个答案:

答案 0 :(得分:3)

你很亲密。您还需要重新定义hash。你的Hash创建中有一对额外的括号。以下作品:

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

有关其他讨论,请参阅Which equality test does Ruby's Hash use when comparing keys?