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

标签 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'
    }
  }
}

到目前为止,我有以下来自 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/

相关文章:

c - 大型数组的频繁随机访问

ruby - 模拟默认对象#inspect 输出?

ruby-on-rails - Rails 定制 "time_ago_in_words"-ish 类型模型

c - 使用相同的指针询问下一个值

arrays - 在 Julia 中初始化一个包含大量数组的空数组

c# - 如何用 Java 或 C# 创建快速 MD5 算法

Ruby Watir 单选框

ruby-on-rails - 为什么 ActiveSupport 将方法 forty_two 添加到 Array

arrays - Mathematica HDF5 和复合数组

hash - JqueryMobile 使用 css3 目标设备