Ruby中hash和eq实现的效果是什么

问题描述 投票:0回答:1
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"}

我期望更换,但没有发生,为什么?

ruby
1个回答
0
投票

当两个对象的

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"}
© www.soinside.com 2019 - 2024. All rights reserved.