-1883761119486508070 "abc".hash => -1883761119486508070 # pry /-6ren">
gpt4 book ai didi

ruby - 为什么 Ruby 的散列方法会因运行而异?

转载 作者:数据小太阳 更新时间:2023-10-29 07:48:28 25 4
gpt4 key购买 nike

# pry / irb example #1
"abc".hash
=> -1883761119486508070
"abc".hash
=> -1883761119486508070

# pry / irb example #2
"abc".hash
=> -4309321811150053495
"abc".hash
=> -4309321811150053495

hash 值对于特定调用是不变的,但在调用之间会有所不同。为什么?这是设计使然吗?这算是“好事”吗?

我正在运行 ruby 1.9.3p194(2012-04-20 修订版 35410)[x86_64-darwin12.0.0]

最佳答案

根据 http://patshaughnessy.net/Ruby-Under-a-Microscope-Rough-Draft-May.pdf 的第 23 页

Here’s how Ruby’s hash function actually works ... [snip] ... For string and arrays it works differently. In this case, Ruby actually iterates through all of the characters in the string or elements in the array and calculates a cumulative hash value; this guarantees that the hash value will always be the same for any instance of a string or array, and will always change if any of the values in that string or array change.

和:

Also, Ruby 1.9 and Ruby 2.0 initialize MurmurHash using a random seed value which is reinitialized each time you restart Ruby. This means that if you stop and restart Ruby you’ll get different hash values for the same input data. It also means if you try this yourself you’ll get different values than I did above. However, the hash values will always be the same within the same Ruby process.

关于ruby - 为什么 Ruby 的散列方法会因运行而异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12172011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com