如何更新循环内的 Ruby 嵌套哈希?
我正在 ruby rexml 中创建一个嵌套哈希,并希望在进入循环时更新哈希。
我的代码是这样的:
hash = {}
doc.elements.each(//address) do |n|
a = # ...
b = # ...
hash = { "NAME" => { a => { "ADDRESS" => b } } }
end
当我执行上面的代码时,哈希值被覆盖,我只得到循环最后一次迭代中的信息。
我不想使用以下方式,因为它使我的代码变得冗长
hash["NAME"] = {}
hash["NAME"][a] = {}
等等...
所以有人可以帮助我如何完成这项工作...
I'm creating a nested hash in ruby rexml and want to update the hash when i enter a loop.
My code is like:
hash = {}
doc.elements.each(//address) do |n|
a = # ...
b = # ...
hash = { "NAME" => { a => { "ADDRESS" => b } } }
end
When I execute the above code the hash gets overwritten and I get only the info in the last iteration of the loop.
I don't want to use the following way as it makes my code verbose
hash["NAME"] = {}
hash["NAME"][a] = {}
and so on...
So could someone help me out on how to make this work...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设名称是唯一的:
Assuming the names are unique:
您始终在每次迭代中创建一个新的哈希值,该哈希值保存在
hash
中。只需直接在现有的
哈希
中分配密钥即可:You always create a new hash in each iteration, which gets saved in
hash
.Just assign the key directly in the existing
hash
:基本上创建一个延迟实例化的无限重复的哈希值。
编辑:只是想到了一些可行的方法,这仅使用几个非常简单的哈希进行了测试,因此可能会出现一些问题。
然后使用 hash.recursive_merge! {“名称”=> { 一个 => {“地址”=> b } } } 在你的代码块中。
如果您在其上定义了
recursive_merge!
和can_recusively_merge?
方法,这将简单地递归合并哈希的层次结构以及任何其他类型。Basically creates a lazily instantiated infinitely recurring hash of hashes.
EDIT: Just thought of something that could work, this is only tested with a couple of very simple hashes so may have some problems.
Then use
hash.recursive_merge! { "NAME" => { a => { "ADDRESS" => b } } }
in your code block.This simply recursively merges a heirachy of hashes, and any other types if you define the
recursive_merge!
andcan_recusively_merge?
methods on them.