如何创建嵌套哈希表

13

我如何在一个哈希中创建一个嵌套的哈希,并且让嵌套的哈希有一个键来标识它?同时,对于我在嵌套哈希中创建的元素,如何给它们分配键呢?

例如:

test = Hash.new()

#create second hash with a name?? test = Hash.new("test1")??
test("test1")[1] = 1???
test("test1")[2] = 2???

#create second hash with a name/key test = Hash.new("test2")???
test("test2")[1] = 1??
test("test2")[2] = 2??

谢谢你


4
欢迎来到SO。如果Joel回答了你的问题,请点击答案旁边的勾选标志将其标记为所选答案。 - pcg79
3个回答

20
my_hash = { :nested_hash => { :first_key => 'Hello' } }

puts my_hash[:nested_hash][:first_key]
$ Hello
或者
my_hash = {}  

my_hash.merge!(:nested_hash => {:first_key => 'Hello' })

puts my_hash[:nested_hash][:first_key]
$ Hello

4
在“新”的1.9语法中,h = {car: {tires: "Michelin", engine: "Wankel"}}可以翻译为:h = {汽车: {轮胎: "米其林",发动机: "旋转式"}} - Jonas Elfström
只是为了澄清,{ tires: 1 } 等同于 { :tires => 1 },并且可以使用 hash[:tires] 检索值。只需将冒号移动到名称的末尾,并删除 => 即可。 - Kudu

20

我会选择Joel的方法,但也可以这样做:

test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'

6
h1 = {'h2.1' => {'foo' => 'this', 'cool' => 'guy'}, 'h2.2' => {'bar' => '2000'} }
h1['h2.1'] # => {'foo' => 'this', 'cool' => 'guy'}
h1['h2.2'] # => {'bar' => '2000'}
h1['h2.1']['foo'] # => 'this'
h1['h2.1']['cool'] # => 'guy'
h1['h2.2']['bar'] # => '2000'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接