繁体   English   中英

遍历数组内深度嵌套的哈希散列的问题

[英]Issues iterating over deeply nested hash of hashes inside an array

因此,我的问题的快速模型可以像这样...

`def problem
  [{
     'Hash1' => {
       'Hash_1' => 'abcd',
       'Hash_2' => 'abcd',
       'Hash_3' => nil,
     }
   },
   {
     'Hash2' => {
       'Hash_1' => 'efg',
       'Hash_2' => 'efg',
       'Hash_3' => 'efg'
     }
   },
   {
     'Hash3' => {
       'Hash_1' => 'hijk',
       'Hash_2' => nil,
       'Hash_3' => 'hijk'
     }
   }]
end`

例如,我想使用.each方法在所有3个哈希中为每个实例查找Hash2的值。

当我这样做时,到处都会返回Nil值。 另外,如果hash2具有nil值,我想返回N/A而不是nil

   problem.each do |item|
    item.each do |thing|
      thing.each do |other_thing|
        puts other_thing['Hash1']
      end
    end
   end

返回以下内容:

Hash1
abcd

efg

hijk

空格nil值。 我很沮丧。 有人想对此进行破解吗?

您将puts未定义的变量,而无需任何条件检查

以上述数据为例:

problem.each do |arr_item|
  arr_item.each do |hash_key, hash|
    if hash['Hash_2']
      puts hash['Hash_2']
    else
      puts 'N/A'
    end
  end
end
arr = [{ 'Hash1'=>{ 'Hash_1'=>'abcd', 'Hash_2'=>'abcd', 'Hash_3'=>nil    } },
       { 'Hash2'=>{ 'Hash_1'=>'efg',  'Hash_2'=>'efg',  'Hash_3'=>'efg'  } },
       { 'Hash3'=>{ 'Hash_1'=>'hijk', 'Hash_2'=>nil,    'Hash_3'=>'hijk' } }
      ]

arr.map { |h| h.first.last["Hash_2"] || 'N/A' }
  #=> ["abcd", "efg", "N/A"] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM