What is the easiest way to convert
[x1, x2, x3, ... , xN]
to
[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]
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.
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.
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] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With