2011-06-22 97 views
10

我如何能够在散列内创建散列,并且嵌套散列具有用于标识它的键。另外,我在嵌套哈希创建的元素,我怎么能对他们有键以及如何在散列内创建散列

例如

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

回答

19
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 
+3

或在“新的”1.9语法中,h = {car:{tyres:“Michelin”,engine:“Wankel”}}' –

+0

为了澄清,{tyres:1}等同于{:tyres => 1 },并且可以使用hash [:tires]检索值。只要将冒号移动到名称的末尾,然后删除'=>'。 – Kudu

13

乔尔的是我会做的,但也可以这样做:

test = Hash.new() 
test['test1'] = Hash.new() 
test['test1']['key'] = 'val' 
4
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'