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

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
paul
  • 133
  • 1
  • 1
  • 4
  • 4
    Welcome to SO. If Joel has answered your question, click the check mark next to the answer to mark it as the chosen answer. – pcg79 Jun 22 '11 at 18:24

3 Answers3

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
Joel AZEMAR
  • 2,506
  • 25
  • 31
  • 4
    Or in the "new" 1.9-syntax `h = {car: {tires: "Michelin", engine: "Wankel"}}` – Jonas Elfström Jun 22 '11 at 15:47
  • 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 `=>`. – Kudu Jun 22 '11 at 18:54
20

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

test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'
glortho
  • 13,120
  • 8
  • 49
  • 45
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'
Kudu
  • 6,570
  • 8
  • 27
  • 27