【问题标题】:How to access assoc array within assoc array如何访问 assoc 数组中的 assoc 数组
【发布时间】:2013-03-03 19:17:33
【问题描述】:

我有以下代码:

def operation hash
  puts hash[:three][:three][:three]
end

operation :one => 'item', :two => [1,2,3], :three => [
    :one => 1,
    :two => 2,
    :three => [
        :one => 1,
        :two => 2,
        :three => [
            :test1,
            :test2
        ]
    ]
]

我想访问项目 hash[:three][:three][:three] 以输出 [test1, test2]。
为什么它不起作用?

【问题讨论】:

    标签: ruby arrays hash multidimensional-array


    【解决方案1】:

    Hash 需要用大括号 {} 括起来,而不是括号 [],后者是为数组保留的。

    与 PHP 不同,在 Ruby 中,这些是不同的类型。

    【讨论】:

      【解决方案2】:

      试试这个:

       def operation hash
        puts hash[:three][0][:three][0][:three]  #=> [:test1, :test2]
      end
      

      请注意,每个 :three 键都有一个存储值的数组。

      【讨论】:

      • 其实没有。每个数组仅包含 1 个元素,因此索引为 0。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      相关资源
      最近更新 更多