在Ruby中,如何为嵌套哈希设置默认值?

In Ruby, how to set a default value for a nested hash?

我最近在 Ruby 中寻找一种正确创建和使用嵌套哈希的方法。我很快找到了一个 solution by Paul Morie,他回答了他自己的问题: hash = Hash.new { |h,k| h[k] = {} }

我立即开始使用它,很高兴地报告它有效。但是,正如标题所说,我希望 the "secondary", "inside" hashes to return 0 default.

我知道您可以在其构造函数 ("Hash.new(0)") 或使用 .default ("hash.default(0) 中定义哈希的默认 return 值]").

但是如何使用散列中的散列来做到这一点?

显然我只需要做:

hash = Hash.new { |h,k| h[k] = Hash.new(0) }

哎呀。下次我会尽量不急着问的。