how to create hash within hash
Asked Answered
N

3

13

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

Novel answered 22/6, 2011 at 15:30 Comment(1)
Welcome to SO. If Joel has answered your question, click the check mark next to the answer to mark it as the chosen answer.Ventilation
I
20
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
Isomerism answered 22/6, 2011 at 15:34 Comment(2)
Or in the "new" 1.9-syntax h = {car: {tires: "Michelin", engine: "Wankel"}}Boletus
Just to clarify, { tires: 1 } is equivalent to { :tires => 1 }, and the value can be retrieved using hash[:tires]. Just move the colon to the end of the name, and drop the =>.Caftan
S
20

Joel's is what I would do, but could also do this:

test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'
Shoestring answered 22/6, 2011 at 15:36 Comment(0)
C
6
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'
Caftan answered 22/6, 2011 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.