我有一个嵌套数组:
[["Area1",["location1", "location2", "location3"]],["Area2",["location4", "location5", "location6"]]]
如何为此数组中的位置添加索引,使其看起来像:
[["Area1",[["location1",1], ["location2",2], ["location3",3]]],["Area2",[["location4",4], ["location5",5], ["location6",6]]]]
答案 0 :(得分:3)
您需要将索引保存为变量,并在迭代元素时对其进行维护:
arr = [["Area1",["location1", "location2", "location3"]],["Area2",["location4", "location5", "location6"]]]
i = 0
arr.each do |area, locations|
locations.map! { |loc| [loc, i = i + 1] }
end
# => [["Area1", [["location1", 1], ["location2", 2], ["location3", 3]]], ["Area2", [["location4", 4], ["location5", 5], ["location6", 6]]]]