snippetrubyCritical
How to map/collect with index in Ruby?
Viewed 0 times
indexwithhowcollectrubymap
Problem
What is the easiest way to convert
to
[x1, x2, x3, ... , xN]to
[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]Solution
If you're using ruby 1.8.7 or 1.9, you can use the fact that iterator methods like
In 1.8.6 you can do:
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] }Code Snippets
arr.each_with_index.map { |x,i| [x, i+2] }require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }Context
Stack Overflow Q#4697557, score: 932
Revisions (0)
No revisions yet.