在Ruby中迭代深度嵌套级别的哈希 [英] Iterate over a deeply nested level of hashes in Ruby
问题描述
{
:key1 => 'value1',
:key2 => 'value2',
:key3 => {
:key4 => 'value4',
:key5 => 'value5'
},
:key6 => {
:key7 => 'value7',
:key8 => {
:key9 => 'value9'
}
}
}
等等。我想要做的是保存每个键,值对和它的父代的id。我想这可能会递归地完成,我只是不确定,因为我不熟悉递归函数。我知道如何正常地遍历数据:
myHash.each {| key,value |
...使用键和值执行操作...
}
所以我猜这个递归调用会是这样的:
def save_pair(myHash)
myHash .each {| key,value |
if(value.class!= Hash)? Pair.create(key,value):save_pair(value)
}
end
<这是未经测试的,我仍然不确定如何合并保存父ID。
目标,那么你应该能够将父母传递给你的保存方法。对于最高级别,它将是零。下面显示了 puts
用作保存的占位符的概念。
def save_pair(parent,myHash)
myHash.each {| key,value |
value.is_a?(哈希)? save_pair(key,value):
puts(parent =#{parent.nil?'none':parent},(#{key},#{value}))
}
end
以下是一个示例调用:
hash = Hash.new
hash [key1] =value1
hash [key2] =value2
hash [key3] = Hash.new
hash [key3] [key4] =value4
hash [key3] [key5] =value5
hash [key6] = Hash.new
hash [key6] [key7] =value7
hash [key6] [key8] =散列。新
hash [key6] [key8] [key9] =value9
save_pair(零,散列)
So I have a hash, and for each level of the hash, I want to store its key and value. The problem is, a value can be another hash array. Furthermore, that hash can contain key value pairs where the value is again another hash array, etc, etc. Also, I won't know how deeply nested each hash will be. To give an example:
{
:key1 => 'value1',
:key2 => 'value2',
:key3 => {
:key4 => 'value4',
:key5 => 'value5'
},
:key6 => {
:key7 => 'value7',
:key8 => {
:key9 => 'value9'
}
}
}
..And so on. What I want to do is save each key, value pair and the id of its parent. I figure this will probably be done recursively, I'm just unsure how because I'm unfamiliar with recursive functions. I know how to iterate through the data normally:
myHash.each {|key, value|
...Do something with the key and value ...
}
And so I'm guessing the recursive call will be something like this:
def save_pair (myHash)
myHash.each {|key, value|
if(value.class != Hash) ? Pair.create(key, value) : save_pair(value)
}
end
This is untested, and I'm still unsure how to incorporate saving the parent ids regardless.
If I understand the goal, then you should be able to pass in the parent to your save method. For the top level, it will be nil. The following shows the idea where puts
is used as a place holder for the "save".
def save_pair(parent, myHash)
myHash.each {|key, value|
value.is_a?(Hash) ? save_pair(key, value) :
puts("parent=#{parent.nil? ? 'none':parent}, (#{key}, #{value})")
}
end
Here is an example call to it:
hash = Hash.new
hash["key1"] = "value1"
hash["key2"] = "value2"
hash["key3"] = Hash.new
hash["key3"]["key4"] = "value4"
hash["key3"]["key5"] = "value5"
hash["key6"] = Hash.new
hash["key6"]["key7"] = "value7"
hash["key6"]["key8"] = Hash.new
hash["key6"]["key8"]["key9"] = "value9"
save_pair(nil, hash)
这篇关于在Ruby中迭代深度嵌套级别的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!