Question

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
Was it helpful?

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

OTHER TIPS

The way you build the hash seems to be functional. What probably causes the error is this loop:

found.each do |k, v, y|

Hash#each yields key/value pairs, so y will be assigned nil, thus causing the error two lines below. What you probably meant is a nested loop like

found.each do |x, h1|
  h1.each do |y, h2|
    puts h2['name1']
  end
end

You should also be aware that you can write these kinds of counting loops more concisely in Ruby:

found = Hash.new { |h,k| h[k] = {} }

1.upto(3) do |x|
  1.upto(3) do |y|
    found[x][y] = {
      'name1' => 'abc1',
      'name2' => 'abc2',
      'name3' => 'abc3',
    }
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top