今天在我们跨多台服务器部署的应用程序上遇到了这个问题。我正在散列一些字符串以存储在共享键/值存储中。 String 的 .hash 方法根据服务器返回不同的整数。任何想法为什么?请注意,我对为什么感兴趣;无法解决。
例子:
server1 $ ruby -v
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]
server1 $ irb
irb(main):001:0> "test".hash
=> 4146582576695053125
server2 $ ruby -v
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]
server2 $ irb
"test".hash
=> 3479379392688537032
这些机器是具有相同规范和构建的 EC2 实例。
最佳答案
来自 Ruby forum 中的 Ruby 开发人员:
It is intended. Ruby 1.9 explicitly use session local random seed to calculate a hash for strings (and some other objects).
This is because the implementation of Object#hash is different between versions (like 1.9.1 and 1.9.2) and implementations (like JRuby, Rubinius, IronRuby, and so on). We want people to write portable code around Object#hash, so we did so.
You should use Digest::SHA256 or some other digest routines when you want some hash value (message digest).
另一个开发者的跟进:
Also, it helps to avoid some denial of service attacks, such as registering hundreds and thousands of users with usernames that have the same hash code.
关于ruby - 为什么 Ruby String.hash 跨机器不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6783811/