2011-06-22 49 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'