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 = ["a", "b", "c"]
(0...arr.length).map do |int|
[arr[int], int + 2]
end
#=> [["a", 2], ["b", 3], ["c", 4]]
Instead of directly iterating over the elements of the array, you're iterating over a range of integers and using them as the indices to retrieve the elements of the array.
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 anEnumerator
object, which you can callEnumerable
methods likemap
on. So you can do:In 1.8.6 you can do:
Ruby has Enumerator#with_index(offset = 0), so first convert the array to an enumerator using Object#to_enum or Array#map:
A fun, but useless way to do this:
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| ... }
I often do this:
Instead of directly iterating over the elements of the array, you're iterating over a range of integers and using them as the indices to retrieve the elements of the array.