迭代包含哈希和/或数组的嵌套哈希

use*_*908 7 ruby arrays hash nested

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

在检查了这个网站和几个样本后,我得到了关键和值.但是如果它的一系列哈希值很难提取.

例:

{
  :key1 => 'value1',
  :key2 => 'value2',
  :key3 => {
    :key4 => [{:key4_1 => 'value4_1', :key4_2 => 'value4_2'}],
    :key5 => 'value5'
  },
  :key6 => {
    :key7 => [1,2,3],
    :key8 => {
      :key9 => 'value9'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我在下面的代码中如何循环遍历ruby中的哈希散列迭代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
Run Code Online (Sandbox Code Playgroud)

但它失败的v.is_hash?(Array)v.is_a?(Array).

我错过了什么吗?

Bea*_*rtz 19

这是不完全清楚,你可能想要的东西,但都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
Run Code Online (Sandbox Code Playgroud)