How to map with index in Ruby?

前端 未结 10 648
走了就别回头了
走了就别回头了 2020-12-07 06:59

What is the easiest way to convert

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

to

[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]
相关标签:
10条回答
  • 2020-12-07 07:44

    Over the top obfuscation:

    arr = ('a'..'g').to_a
    indexes = arr.each_index.map(&2.method(:+))
    arr.zip(indexes)
    
    0 讨论(0)
  • 2020-12-07 07:46

    A fun, but useless way to do this:

    az  = ('a'..'z').to_a
    azz = az.map{|e| [e, az.index(e)+2]}
    
    0 讨论(0)
  • 2020-12-07 07:47

    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]]
    
    0 讨论(0)
  • 2020-12-07 07:51
    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]]
    
    0 讨论(0)
提交回复
热议问题