Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]] 
like image 893
Misha Moroshko Avatar asked Jan 15 '11 01:01

Misha Moroshko


People also ask

How do I make a map in Ruby?

The way the map method works in Ruby is, it takes an enumerable object, (i.e. the object you call it on), and a block. Then, for each of the elements in the enumerable, it executes the block, passing it the current element as an argument. The result of evaluating the block is then used to construct the resulting array.

How do you create an index in Ruby?

Ruby | Array class find_index() operation Array#find_index() : find_index() is a Array class method which returns the index of the first array. If a block is given instead of an argument, returns the index of the first object for which the block returns true.


1 Answers

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] } 
like image 144
sepp2k Avatar answered Sep 30 '22 07:09

sepp2k