设置哈希的默认值,如下所示:
hash = Hash.new { |hsh, key| hsh[key] = {} }
将为未知密钥创建(并分配)新哈希,但会为创建的哈希的未知密钥返回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] #=> {}
答案 0 :(得分:6)
思维弯曲的类型,但您可以将哈希值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=>{}}}}
答案 1 :(得分:3)
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] # => {}
答案 2 :(得分:2)
您可以使用Recursion
创建method
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: {}}}}}