2012-03-27 60 views
0

我有这样的代码:为什么字符串散列会改变?

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 

为什么哈希码改变每个呼叫?

我认为它应该保持与Java中的String哈希码相同。或者,哈希码正在改变,因为每次调用都会给我新的实例foldername? Ruby的String类型具有散列方法的实现,所以相同的字符串应该为每个调用提供相同的编号。

回答

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 
+1

正在我的路上说同样的事情。我建议海报使用'Digest :: SHA1'或者其他等效物。有关相关信息,请参阅http://stackoverflow.com/questions/4452161/do-ruby-1-8-and-1-9-have-the-same-hash-code-for-a-string。 – Emily 2012-03-27 15:19:12

+0

感谢发布,自动转至我的最爱问题 – bodo 2012-03-27 15:29:10

+3

这是一项安全功能。如果哈希值可以预测,恶意用户可以预先计算大量具有相同哈希值的字符串,并将它们提供给您的应用程序,从而影响性能。 – steenslag 2012-03-27 15:38:18

相关问题