使用each_with_index将索引放在第一位

时间:2012-06-12 17:49:39

标签: ruby

我正在使用带有each_with_index的Array()来输出带索引的数组,但我希望它输出

[[0,obj1],[1,obj2]....] 

而each_with_index使其输出

[[obj1,0],[obj2,1]....] 

无论如何,这可以修复吗?

被要求显示代码。

Array(test.each_with_index)

2 个答案:

答案 0 :(得分:3)

尝试在.map { |x| x.reverse }之后添加each_with_index

答案 1 :(得分:0)

使用此:

[obj1, obj2, ..., objN].map.with_index{|a,i| [i,a] }
#=> [[0, obj1], [1, obj2], ..., [N-1, objN]]
相关问题