How to map with index in Ruby?

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

提交回复
热议问题