13

我如何能够在散列中创建散列,嵌套散列具有标识它的键。还有我在嵌套哈希中创建的元素,我怎么能有它们的键

例如

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

谢谢你

4

3 回答 3

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

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

或者

my_hash = {}  

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

puts my_hash[:nested_hash][:first_key]
$ Hello
于 2011-06-22T15:34:49.480 回答
20

Joel's 是我会做的,但也可以这样做:

test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'
于 2011-06-22T15:36:43.283 回答
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'
于 2011-06-22T15:39:44.720 回答