How to map with index in Ruby?

2019-01-20 21:39发布

What is the easiest way to convert

[x1, x2, x3, ... , xN]

to

[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]

10条回答
欢心
2楼-- · 2019-01-20 21:51

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] }
查看更多
淡お忘
3楼-- · 2019-01-20 21:51

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]]
查看更多
Anthone
4楼-- · 2019-01-20 21:53
module Enumerable
  def map_with_index(&block)
    i = 0
    self.map { |val|
      val = block.call(val, i)
      i += 1
      val
    }
  end
end

["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-20 21:53

A fun, but useless way to do this:

az  = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}
查看更多
仙女界的扛把子
6楼-- · 2019-01-20 22:07

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| ... }

查看更多
放荡不羁爱自由
7楼-- · 2019-01-20 22:09

I often do this:

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.

查看更多
登录 后发表回答