pau*_*aul 12 ruby hash ruby-on-rails 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??
Run Code Online (Sandbox Code Playgroud)
谢谢
Joe*_*MAR 21
my_hash = { :nested_hash => { :first_key => 'Hello' } }
puts my_hash[:nested_hash][:first_key]
$ Hello
Run Code Online (Sandbox Code Playgroud)
要么
my_hash = {}
my_hash.merge!(:nested_hash => {:first_key => 'Hello' })
puts my_hash[:nested_hash][:first_key]
$ Hello
Run Code Online (Sandbox Code Playgroud)
glo*_*tho 18
Joel是我会做的,但也可以这样做:
test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)