如何在哈希中创建哈希

时间:2011-06-22 15:30:09

标签: ruby-on-rails ruby hash hash-of-hashes

如何在哈希中创建哈希,嵌套哈希有一个键来识别它。我在嵌套哈希中创建的元素也是如何为它们设置键

例如

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

谢谢

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:18)

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

test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'

答案 2 :(得分:5)

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'