How to map with index in Ruby?

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

    Here are two more options for 1.8.6 (or 1.9) without using enumerator:

    # Fun with functional
    arr = ('a'..'g').to_a
    arr.zip( (2..(arr.length+2)).to_a )
    #=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]
    
    # The simplest
    n = 1
    arr.map{ |c| [c, n+=1 ] }
    #=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]
    
    0 讨论(0)
  • 2020-12-07 07:32
    a = [1, 2, 3]
    p [a, (2...a.size+2).to_a].transpose
    
    0 讨论(0)
  • 2020-12-07 07:37

    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| ... }
    
    0 讨论(0)
  • 2020-12-07 07:38

    I have always enjoyed the syntax of this style:

    a = [1, 2, 3, 4]
    a.each_with_index.map { |el, index| el + index }
    # => [1, 3, 5, 7]
    

    Invoking each_with_index gets you an enumerator you can easily map over with your index available.

    0 讨论(0)
  • 2020-12-07 07:38

    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.

    0 讨论(0)
  • 2020-12-07 07:43

    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] }
    
    0 讨论(0)
提交回复
热议问题