How to map with index in Ruby?
What is the easiest way to convert
[x1, x2, x3, ... , xN]
to
[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]
Solution 1:
If you're using ruby 1.8.7 or 1.9, you can use the fact that iterator methods like each_with_index
, when called without a block, return an Enumerator
object, which you can call Enumerable
methods like map
on. So you can do:
arr.each_with_index.map { |x,i| [x, i+2] }
In 1.8.6 you can do:
require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }
Solution 2:
Ruby has Enumerator#with_index(offset = 0), so first convert the array to an enumerator using Object#to_enum or Array#map:
[:a, :b, :c].map.with_index(2).to_a
#=> [[:a, 2], [:b, 3], [:c, 4]]
Solution 3:
In ruby 1.9.3 there is a chainable method called with_index
which can be chained to map.
For example:
array.map.with_index { |item, index| ... }
Solution 4:
Over the top obfuscation:
arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)