最简单的转换方法是什么
[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]]
当前回答
如果你使用的是ruby 1.8.7或1.9,你可以使用像each_with_index这样的迭代器方法,当不带块调用时,返回一个Enumerator对象,你可以调用像map on这样的Enumerable方法。所以你可以这样做:
arr.each_with_index.map { |x,i| [x, i+2] }
在1.8.6中,你可以做到:
require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }
其他回答
一种有趣但无用的方法:
az = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}
如果你使用的是ruby 1.8.7或1.9,你可以使用像each_with_index这样的迭代器方法,当不带块调用时,返回一个Enumerator对象,你可以调用像map on这样的Enumerable方法。所以你可以这样做:
arr.each_with_index.map { |x,i| [x, i+2] }
在1.8.6中,你可以做到:
require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }
在ruby 1.9.3中,有一个名为with_index的可链接方法,可以链接到map。
例如:
array.map.with_index { |item, index| ... }
最令人困惑的是:
arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)
a = [1, 2, 3]
p [a, (2...a.size+2).to_a].transpose