最简单的转换方法是什么
[x1, x2, x3, ... , xN]
to
[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]
最简单的转换方法是什么
[x1, x2, x3, ... , xN]
to
[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]
当前回答
最令人困惑的是:
arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)
其他回答
最令人困惑的是:
arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)
在ruby 1.9.3中,有一个名为with_index的可链接方法,可以链接到map。
例如:
array.map.with_index { |item, index| ... }
Ruby有枚举器#with_index(offset = 0),所以首先使用Object#to_enum或array #map将数组转换为枚举器:
[:a, :b, :c].map.with_index(2).to_a
#=> [[:a, 2], [:b, 3], [:c, 4]]
一种有趣但无用的方法:
az = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}
下面是1.8.6(或1.9)中不使用枚举器的另外两个选项:
# Fun with functional
arr = ('a'..'g').to_a
arr.zip( (2..(arr.length+2)).to_a )
#=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]
# The simplest
n = 1
arr.map{ |c| [c, n+=1 ] }
#=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]