2012-06-28 12 views
5

我有一個包裝類,我想在哈希中用作鍵。包裝和解包器對象應映射到相同的密鑰。在比較密鑰時,Ruby的Hash使用哪種相等性測試?

一個簡單的例子是這樣的:

class A 
    attr_reader :x 
    def initialize(inner) 
    @inner=inner 
    end 
    def x; @inner.x; end 
    def ==(other) 
    @inner.x==other.x 
    end 
end 
a = A.new(o) #o is just any object that allows o.x 
b = A.new(o) 
h = {a=>5} 
p h[a] #5 
p h[b] #nil, should be 5 
p h[o] #nil, should be 5 

我試過==,===,情商?並散列所有無濟於事。

+1

你可能想看看'SimpleDelegator',如果你想委派最方法'@ inner'。 –

+0

謝謝@ Marc-AndréLafortune!今天學到了新東西 – alexloh

回答

4

哈希使用key.eql?測試鍵是否相等。如果您需要使用您自己的類的實例作爲哈希中的鍵,則建議您使用 來定義eql?和散列方法。散列方法必須 具有a.eql?(b)意味着a.hash == b.hash的屬性。

所以......

class A 
    attr_reader :x 
    def initialize(inner) 
    @inner=inner 
    end 
    def x; @inner.x; end 
    def ==(other) 
    @inner.x==other.x 
    end 

    def eql?(other) 
    self == other 
    end 

    def hash 
    x.hash 
    end 
end 
+0

啊,所以它同時使用。現在我想到了,使用'hash'來獲取桶,然後使用'eql?'來進行實際測試是有意義的。我認爲它在Java中也是一樣的 – alexloh

+0

但是爲什麼'eq?'的默認實現不使用'=='? – ony