blk = proc { |hash, key| hash[key] = Hash.new(&blk) }
hash = Hash.new(&blk)
doc.elements.each('//address').each do |n|
a = # ...
b = # ...
hash["NAME"][a]["ADDRESS"] = b
end
基本上创建了一个惰性实例化的无限循环哈希。
编辑:只是想到了一些可行的方法,这只用几个非常简单的哈希进行了测试,所以可能会有一些问题。
class Hash
def can_recursively_merge? other
Hash === other
end
def recursive_merge! other
other.each do |key, value|
if self.include? key and self[key].can_recursively_merge? value
self[key].recursive_merge! value
else
self[key] = value
end
end
self
end
end
然后hash.recursive_merge! { "NAME" => { a => { "ADDRESS" => b } } }
在您的代码块中使用。
这只是递归地合并一系列散列,以及任何其他类型(如果您在它们上定义recursive_merge!
andcan_recusively_merge?
方法)。