我有这个代码:
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哈希代码保持一致.或者,哈希码正在改变,因为每次调用都会给我新的实例folder和name?Ruby的String类型具有hash方法的实现,因此相同的String应该为每个调用提供相同的数字.
相同的字符串不会在两个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)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           315 次  |  
        
|   最近记录:  |