如何更新循环中的Ruby嵌套哈希?

时间:2011-05-12 10:09:37

标签: ruby rexml

我正在ruby rexml中创建一个嵌套哈希,并希望在我进入循环时更新哈希值。

我的代码就像:

hash = {}
doc.elements.each(//address) do |n|
  a = # ... 
  b = # ...
  hash = { "NAME" => { a => { "ADDRESS" => b } } }
end

当我执行上面的代码时,哈希被覆盖,我只得到循环最后一次迭代中的信息。

我不想使用以下方式,因为它使我的代码详细

hash["NAME"] = {}
hash["NAME"][a] = {} 

依旧......

所以有人可以帮我解决如何使这项工作......

4 个答案:

答案 0 :(得分:0)

假设名称是唯一的:

hash.merge!({"NAME" => { a => { "ADDRESS" => b } } })

答案 1 :(得分:0)

您总是在每次迭代中创建一个新哈希,并将其保存在hash

只需直接在现有hash

中分配密钥即可
hash["NAME"] = { a => { "ADDRESS" => b } }

答案 2 :(得分:0)

hash = {"NAME" => {}}

doc.elements.each('//address') do |n|
  a = ...
  b = ...
  hash['NAME'][a] = {'ADDRESS' => b, 'PLACE' => ...}
end

答案 3 :(得分:0)

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!can_recusively_merge?方法,这只是递归地合并哈希的哈希,以及任何其他类型。

相关问题