2011-06-22 21 views
10

¿Cómo puedo crear un hash dentro de un hash, con el hash anidado que tiene una clave para identificarlo? También los elementos que crean en el resumen anidada, ¿cómo puedo tener claves para ellos tambiéncómo crear hash dentro de hash

por ejemplo

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

gracias

+4

Bienvenido a SO. Si Joel ha respondido su pregunta, haga clic en la marca de verificación junto a la respuesta para marcarla como la respuesta elegida. – pcg79

Respuesta

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

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

o

my_hash = {} 

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

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

O en la "nueva" sintaxis 1.9 'h = {coche: {neumáticos:" Michelin ", motor:" Wankel "}}' –

+0

Solo para aclarar, {tires: 1} es equivalente a {: tires => 1 }, y el valor se puede recuperar usando hash [: tires]. Simplemente mueva los dos puntos hasta el final del nombre y suelte '=>'. – Kudu

13

Joel es lo que yo haría, pero también podría hacer esto:

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'