How to map with index in Ruby?

前端 未结 10 650
走了就别回头了
走了就别回头了 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: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]]
    

提交回复
热议问题