哈希默认值是具有相同默认值的哈希

Hash default value is a hash with same default value

像这样设置散列的默认值:

hash = Hash.new { |hsh, key| hsh[key] = {} }

将为未知密钥创建(并分配)新哈希,但将为已创建哈希的未知密钥return nil

hash[:unkown_key] #=> {}
hash[:unkown_key][:nested_unknown] #=> nil

我可以像这样让它在第二层工作:

hash = Hash.new do |hsh, key|
  hsh[key] = Hash.new { |nest_hsh, nest_key| nest_hsh[nest_key] = {} }
end

但是,它在第​​三层不起作用:

hash[:unkown_key][:nested_unknown] #=> {}
hash[:unkown_key][:nested_unknown][:third_level] #=> nil

如何让它在任意级别工作?

hash[:unkown_key][:nested_unknown][:third_level][...][:nth_level] #=> {}
bottomless_hash = ->() do
  Hash.new { |h, k| h[k] = bottomless_hash.call }
end

hash = bottomless_hash.call
hash[:unkown_key][:nested_unknown][:third_level][:fourth] # => {}

您可以创建 method 来使用 Recursion

class Hash
  def self.recursive
    new { |hash, key| hash[key] = recursive }
  end
end

hash = Hash.recursive
hash[:unknown_key] # => {}
hash[:first_unknown_key][:second_unknown_key][...][:infinity]
# hash => {first_unknown_key:  {second_unknown_key: {... {infinity: {}}}}}

有点费脑筋,但您可以将散列的 default_proc 传递给内部散列:

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

hash[:foo] #=> {}
hash[:foo][:bar] #=> {}
hash[:foo][:bar][:baz] #=> {}

hash #=> {:foo=>{:bar=>{:baz=>{}}}}