2011-06-22 26 views
10

Bir karma içinde bir karma oluşturabilir, iç içe geçmiş hash, bunu belirtmek için bir anahtara sahip olur. Ayrıca ben iç içe karma oluşturmak elemanları, nasılhash içinde karma oluşturma

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?? 

size

+4

SO. Eğer Joel sorunuzu cevapladıysa, cevabın yanındaki onay işaretini, seçilen cevap olarak işaretlemek için tıklayın. – pcg79

cevap

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

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

veya

my_hash = {} 

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

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

Veya "yeni" 1.9-syntax 'h = {car: {tire:" Michelin ", motor:" Wankel "}}' –

+0

Sadece netleştirmek için, {tire: 1} {: tires => 1'e eşdeğerdir } ve değer hash [: tires] kullanılarak alınabilir. Sadece sütunu ismin sonuna taşıyın ve '=>' ifadesini bırakın. – Kudu

13

teşekkür onlar için anahtarları yanı örneğin

olabilir Joel'in yapacağı şey buydu ama bunu da yapabilirdi:

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'