【问题标题】:how to create hash within hash如何在哈希中创建哈希
【发布时间】:2011-09-20 12:17:00
【问题描述】:

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

例如

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

谢谢

【问题讨论】:

  • 欢迎来到 SO。如果 Joel 回答了您的问题,请单击答案旁边的复选标记以将其标记为所选答案。

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


【解决方案1】:
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.9-语法h = {car: {tires: "Michelin", engine: "Wankel"}}
  • 澄清一下,{ Tires: 1 } 等价于 { :tires => 1 },并且可以使用 hash[:tires] 检索该值。只需将冒号移到名称的末尾,然后删除 =>
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    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-04-20
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2016-09-21
      • 2012-01-02
      • 1970-01-01
      相关资源
      最近更新 更多