必须一直初始化子元素是多余的。我的意思是:
@parent = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }
如果我尝试创建另一个多维节点,我会尝试编码:
@parent[:child][some_field] = "Some example data..."
我总是收到这个错误:
undefined method `[]=' for nil:NilClass (NoMethodError)
你有什么解决办法吗?
最佳答案
我经常需要嵌套哈希,为什么不定义自己的类?
class NestedHash < Hash
def initialize
super { |h,k| h[k] = Hash.new(&h.default_proc) }
end
end
h = NestedHash.new
h[:foo][:bar] = :baz
h[:foo][:bar] #=> :baz
关于ruby - 有没有办法初始化哈希的所有子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34239611/