Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 395
Alfons Avatar asked Nov 20 '25 10:11

Alfons


1 Answers

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
like image 99
opsb Avatar answered Nov 22 '25 00:11

opsb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!