我有一个像这样的多维数组,这是一组纬度和经度。
multi = [[12.96145, 77.58408],[12.96219, 77.58447],[12.96302, 77.58489],[12.96316, 77.58496],[12.96348, 77.58511],[12.96356, 77.58512],[12.96363, 77.5851],[12.96372, 77.58506],[12.96376, 77.58497],[12.96374, 77.58479]]
我想将上面的数组转换为单个变量,如下所示:
lat1 = 12.96145
lon1 = 77.58408
lat2 = 12.96219
lon2 = 77.58447
.
.
我试图通过如下的漫长程序来实现上述目标。我希望肯定会有更好的方法来做到这一点。
l1,l2,l3,l4,l5,l6,l7,l8,l9,l10 = multi
lat1 = l1.first
lon1 = l1.last
lat2 = l2.first
lon2 = l2.last
.
.
答案 0 :(得分:1)
lat1, lon1,
lat2, lon2,
...
latn, lonn,
= multi.flatten
或
(lat1, lon1),
(lat2, lon2),
...
(latn, lonn),
= multi
答案 1 :(得分:1)
也可以为这样的实例变量赋值:
multi.each_with_index do |pair, i|
instance_variable_set("@lat#{i%multi.size+1}", pair.first)
instance_variable_set("@lon#{i%multi.size+1}", pair.last)
end
然后引用变量:@lat1
,@lon1
,...,@latn
,@lonn