class A
def hash
12
end
def ==(other)
true
end
end
x = {}
a = A.new
b = A.new
x[a] = "Hello"
x[b] = "World"
puts x
这是打印:
{#<A:0x000055d1f3985c68>=>"Hello", #<A:0x000055d1f3985830>=>"World"}
我期望更换,但没有发生,为什么?
当两个对象的
值相同并且两个对象彼此hash
时,它们被视为相同的哈希键。eql?
http://www.ruby-doc.com/3.3.0/Hash.html#class-Hash-label-Hash+Key+Equivalence
您必须定义
eql?
而不是 ==
:
class A
def hash
1
end
def eql? other
true
end
end
x = {}
a = A.new
b = A.new
x[a] = "Hello"
x[b] = "World"
p x
#=> {#<A:0x00007fce035af608>=>"World"}