ruby - 为什么 Ruby String.hash 跨机器不一致?

标签 ruby ruby-on-rails-3 hash

今天在我们跨多台服务器部署的应用程序上遇到了这个问题。我正在散列一些字符串以存储在共享键/值存储中。 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/

相关文章:

ruby - 使用 Ruby 从 Windows 文件中提取选定的元数据

ruby - 如何在 Ruby 中找到机器上的可用物理内存?

ruby-on-rails - 如何在 Rails 中启用日志记录?

ruby - 在 Ruby 中创建凯撒密码,出现错误

ruby-on-rails - 将表单发送到其内容的 url

ruby-on-rails - 如何将方法添加到 Paper_trail 的版本模型?

ruby-on-rails - ruby on Rails 应用程序重新启动时执行脚本

Perl:使用哈希值通过引用调用子例程的问题

javascript - 如何在哈希数组中找到最新的日期并返回对应的名称键/值

ruby - 在 Ruby 中减去两个哈希值