Search code examples
rubyhashmaphash-of-hashes

Ruby hash of hash of hash


How can I have a hash of hash of hash?

My test returns

undefined method `[]' for nil:NilClass (NoMethodError)

Any tips?

found = Hash.new()
x = 1;

while x < 4 do
  found[x] = Hash.new()
  y = 1

  while y < 4 do
    found[x][y] = Hash.new()
    found[x][y]['name1'] = 'abc1'
    found[x][y]['name2'] = 'abc2'
    found[x][y]['name3'] = 'abc3'

    y += 1
  end

  x += 1
end

found.each do |k, v, y|
  puts "k : #{k}"
  puts "  : #{v[y['name1']]}"
  puts "  : #{v[y['name2']]}"
  puts "  : #{v[y['name3']]}"
  puts
end

Solution

  • I think you want something like this:

    First of all create the data structure. You want nested hashes so you need to define default values for each hash key.

    found = Hash.new do |hash,key| 
        hash[key] = Hash.new do |hash,key|
            hash[key] = Hash.new
        end
    end
    

    Run the search

    (1..3).each do |x|
      (1..3).each do |y|
        found[x][y]['name1'] = 'abc1'
        found[x][y]['name2'] = 'abc1'
        found[x][y]['name3'] = 'abc1'    
      end
    end
    

    Then display the results

    found.each do |x, y_hash|
      y_hash.each do |y, name_hash|
        name_hash.each do |name, value|
          puts "#{x} => #{y} => #{name} => #{value}"
        end
      end
    end