Ruby 如何在assoc数组中访问assoc数组
我有以下代码:Ruby 如何在assoc数组中访问assoc数组,ruby,arrays,hash,multidimensional-array,Ruby,Arrays,Hash,Multidimensional Array,我有以下代码: 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 =>
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
]
]
]
我想访问项目哈希[:三][:三][:三]以输出[test1,test2]。为什么不起作用?试试这个:
def operation hash
puts hash[:three][0][:three][0][:three] #=> [:test1, :test2]
end
请注意,
:三个
键中的每一个键都有一个存储值的数组。哈希需要用大括号{}
包围,而不是为数组保留的大括号[]
与PHP不同,在Ruby中,这些是不同的类型。实际上不是。每个数组只包含1个元素,因此索引为0。