如何在哈希中创建哈希

发布于 2024-11-16 13:41:53 字数 352 浏览 4 评论 0原文

我如何能够在散列中创建散列,并且嵌套散列具有用于识别它的密钥。还有我在嵌套哈希中创建的元素,我怎样才能拥有它们的键,

例如

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

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你的往事 2024-11-23 13:41:53

乔尔的就是我会做的,但也可以这样做:

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

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

test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'
旧伤慢歌 2024-11-23 13:41:53
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
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
安静被遗忘 2024-11-23 13:41:53
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'
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'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文