0

So, a quick mockup of my issue can look like this ...

`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`

For example, I want to use a .each method to find the value of Hash2 for every instance of it, in all of the 3 hashes.

When I do this I get returned with Nil values everywhere. As an added issue, if hash2 has a nil value, I want to return N/A instead of having nil.

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

Which returns the following:

Hash1
abcd

efg

hijk

The spaces being nil values. I am super stumped. Anyone wanna take a crack at this?

TheRealMrCrowley
  • 976
  • 7
  • 24
vin_Bin87
  • 318
  • 8
  • 18
  • if you need a function to work for a specific set of nesting post the data you need to work with. the answer posted works just fine for the example data – TheRealMrCrowley Feb 05 '17 at 04:01

2 Answers2

1

you are putsing undefined variables without any conditional checking

using the above data as an example:

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
TheRealMrCrowley
  • 976
  • 7
  • 24
0
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"] 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100