how to create hash within hash

paul picture paul · Jun 22, 2011 · Viewed 36.3k times · Source

How am I able to create a hash within a hash, with the nested hash having a key to indentify it. Also the elements that I create in the nested hash, how can I have keys for them as well

for example

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

thank you

Answer

Joel AZEMAR picture Joel AZEMAR · Jun 22, 2011
my_hash = { :nested_hash => { :first_key => 'Hello' } }

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

or

my_hash = {}  

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

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