ruby - 这段 Ruby 代码是如何工作的? (哈希)(Learnrubythehardway)

标签 ruby hash

我知道我看起来像个十足的菜鸟,但有些事情我无法理解。让我强调一下,我确实在谷歌上搜索过这个东西,但没有找到我要找的东西。

我正在学习 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 the aDict.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 是一个数组),它会返回一些内容。 (我的问题并不是完全独立的。)

  1. 它是做什么的以及如何做到这一点? (好的,它返回一个存储桶索引,但是我们如何“到达那里”?)
  2. key.hash 的作用/它是什么?
  3. 使用 % 如何帮助我获得我需要的东西? (用aDict.length“修改”key.hash有什么用?)
  4. “使用 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/

相关文章:

ruby - 如何使用变量通过正则表达式来匹配这段代码?

ruby - 为什么这个 "deaf grandma"程序不正确?

perl - 如何从散列的散列中提取键名?

mysql - 如果我知道分布将不相等,如何计算哈希中的桶数?

ruby-on-rails - Rails 哈希树到数组

ruby - Jekyll 在构建时输出 Gemfile、Gemfile.lock。我该如何/应该如何防止这种情况?

ruby - 我如何在 MiniTest 中 stub ?

ruby-on-rails - 重定向 Rails 3 中特定 Controller 的记录器输出

arrays - 复制数组哈希的前 N ​​个键和值

asp.net - `SecurityStamp` 类上的标识 `User` 是否减少了存储哈希盐的需要?