ruby-on-railsarraysrubyhashhash-of-hashes

Issues iterating over deeply nested hash of hashes inside an array


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?


Solution

  • 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