为什么String哈希值会发生变化?

bod*_*odo 0 ruby hashcode

我有这个代码:

class DocumentIdentifier
  attr_reader :folder, :name

  def initialize( folder, name )
    @folder = folder
    @name = name
  end

  def ==(other)
    return true if other.equal?(self)
    return false unless other.kind_of?(self.class)
    folder == other.folder && name == other.name
  end

  def hash
    folder.hash ^ name.hash
  end

  def eql?(other)
    return false unless other.instance_of?(self.class)
    other.folder == folder && other.name == name
  end
end

first_id = DocumentIdentifier.new('secret/plans', 'raygun.txt')
puts first_id.hash
Run Code Online (Sandbox Code Playgroud)

为什么每次调用的哈希码都在变化?

我认为它应该与Java中的String哈希代码保持一致.或者,哈希码正在改变,因为每次调用都会给我新的实例foldername?Ruby的String类型具有hash方法的实现,因此相同的String应该为每个调用提供相同的数字.

Dog*_*ert 7

相同的字符串不会在两个Ruby会话之间返回相同的哈希值,仅在当前会话中返回.

?  tmp  pry
[1] pry(main)> "foo".hash
=> -3172192351909719463
[2] pry(main)> exit
?  tmp  pry
[1] pry(main)> "foo".hash
=> 2138900251898429379
[2] pry(main)> "foo".hash
=> 2138900251898429379
Run Code Online (Sandbox Code Playgroud)

  • 这是一个安全功能.如果哈希值是可预测的,那么恶意用户可以使用相同的哈希值预先计算大量字符串,并将它们提供给您的应用程序,从而影响性能. (3认同)