Ruby-on-rails 如何在哈希中创建哈希
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6442473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:27:27 来源:igfitidea点击:
how to create hash within hash
提问by paul
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
谢谢你
回答by Joel AZEMAR
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
回答by glortho
Joel's is what I would do, but could also do this:
乔尔是我会做的,但也可以这样做:
test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'
回答by Kudu
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'

