Duplicate elements of array in ruby

后端 未结 4 1178
眼角桃花
眼角桃花 2021-01-25 12:11

I find a lot of reference about removing duplicates in ruby but I cannot find how to create duplicate.

If I have an array like [1,2,3] how can I map it to a

4条回答
  •  日久生厌
    2021-01-25 13:01

    Here's yet another way, creating the array directly with Array#new :

    array = [1, 2, 3]
    repetitions = 2
    
    p Array.new(array.size * repetitions) { |i| array[i / repetitions] }
    # [1, 1, 2, 2, 3, 3]
    

    According to fruity, @ursus's answer, @ilya's first two answers and mine have comparable performance. transpose.flatten is slower than any of the others.

提交回复
热议问题