gpt4 book ai didi

ruby - 迭代包含散列和/或数组的嵌套散列

转载 作者:数据小太阳 更新时间:2023-10-29 06:55:59 24 4
gpt4 key购买 nike

我有一个散列,我正在尝试为它提取键和值。散列具有嵌套散列和/或散列数组。

在检查了这个站点和几个示例之后,我得到了键和值。但如果它是一个哈希数组,则很难提取。

例子:

{
: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) 处失败。

我错过了什么吗?

最佳答案

尚不完全清楚您可能想要什么,但两者都是 ArrayHash实现 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com