最简单的转换方法是什么

[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)

其他回答

a = [1, 2, 3]
p [a, (2...a.size+2).to_a].transpose

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]]

我一直很喜欢这种风格的语法:

a = [1, 2, 3, 4]
a.each_with_index.map { |el, index| el + index }
# => [1, 3, 5, 7]

调用each_with_index可以获得一个枚举数,可以轻松地映射到可用的索引上。

module Enumerable
  def map_with_index(&block)
    i = 0
    self.map { |val|
      val = block.call(val, i)
      i += 1
      val
    }
  end
end

["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]

一种有趣但无用的方法:

az  = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}