作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我有一个散列,我正在尝试为它提取键和值。散列具有嵌套散列和/或散列数组。
在检查了这个站点和几个示例之后,我得到了键和值。但如果它是一个哈希数组,则很难提取。
例子:
{
:key1 => 'value1',
:key2 => 'value2',
:key3 => {
:key4 => [{:key4_1 => 'value4_1', :key4_2 => 'value4_2'}],
:key5 => 'value5'
},
:key6 => {
:key7 => [1,2,3],
:key8 => {
:key9 => 'value9'
}
}
}
到目前为止,我有以下来自 how do i loop over a hash of hashes in ruby 的代码和 Iterate over an deeply nested level of hashes in Ruby
def ihash(h)
h.each_pair do |k,v|
if v.is_a?(Hash) || v.is_a?(Array)
puts "key: #{k} recursing..."
ihash(v)
else
# MODIFY HERE! Look for what you want to find in the hash here
puts "key: #{k} value: #{v}"
end
end
end
但它在 v.is_hash?(Array)
或 v.is_a?(Array)
处失败。
我错过了什么吗?
最佳答案
尚不完全清楚您可能想要什么,但两者都是 Array
和 Hash
实现 each
(在 Hash
的情况下,它是 each_pair
的别名)。
因此,如果您的方法可行,要准确获得您将获得的输出,您可以像这样实现它:
def iterate(h)
h.each do |k,v|
# If v is nil, an array is being iterated and the value is k.
# If v is not nil, a hash is being iterated and the value is v.
#
value = v || k
if value.is_a?(Hash) || value.is_a?(Array)
puts "evaluating: #{value} recursively..."
iterate(value)
else
# MODIFY HERE! Look for what you want to find in the hash here
# if v is nil, just display the array value
puts v ? "key: #{k} value: #{v}" : "array value #{k}"
end
end
end
关于ruby - 迭代包含散列和/或数组的嵌套散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16412013/
我是一名优秀的程序员,十分优秀!