我知道我看起来像个十足的菜鸟,但有些事情我无法理解。让我强调一下,我确实在谷歌上搜索过这个东西,但没有找到我要找的东西。
我正在学习 learnrubythehardway
类(class),并且 ex39这是我们定义的函数之一:
def Dict.hash_key(aDict, key)
return key.hash % aDict.length
end
作者给出了这样的解释:
hash_key This deceptively simple function is the core of how a hash works. What it does is uses the built-in Ruby hash function to convert a string to a number. Ruby uses this function for its own hash data structure, and I'm just reusing it. You should fire up a Ruby console to see how it works. Once I have a number for the key, I then use the
% (modulus)
operator and theaDict.length
to get a bucket where this key can go. As you should know, the% (modulus)
operator will divide any number and give me the remainder. I can also use this as a way of limiting giant numbers to a fixed smaller set of other numbers. If you don't get this then use Ruby to explore it
我喜欢这门类(class),但上面的段落没有帮助。
好的,您调用该函数并向其传递两个参数(aDict
是一个数组),它会返回一些内容。
(我的问题并不是完全独立的。)
- 它是做什么的以及如何做到这一点? (好的,它返回一个存储桶索引,但是我们如何“到达那里”?)
key.hash
的作用/它是什么?- 使用
%
如何帮助我获得我需要的东西? (用aDict.length
“修改”key.hash
有什么用?) - “使用 Ruby 来探索它。” - 好的,但是我的问题二。有点已经暗示我不知道该怎么做。
提前致谢。
最佳答案
key.hash
正在调用 Object#hash ,不要与 Hash 混淆.
Object#hash
将字符串一致地转换为数字(在相同的 Ruby 运行实例中,相同的字符串始终会产生相同的数字)。
pry(main)> "abc".hash
=> -1672853150
现在我们有了一个数字,但对于我们的 Dict
结构中的存储桶数量来说太大了,默认为 256 个存储桶。因此,我们对其取模以获得一个在我们的桶范围内的数字。
pry(main)> "abc".hash % 256
=> 98
这本质上允许我们将 Dict["abc"]
转换为 aDict[98]
。
关于ruby - 这段 Ruby 代码是如何工作的? (哈希)(Learnrubythehardway),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30452704/