[英]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)
未定义的方法`[]'为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
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. Hash#each
产生键/值对,因此y
将被指定为nil
,从而导致错误下面两行。 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: 您还应该知道,您可以在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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.