Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate elements of array in ruby

Tags:

ruby

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 an array with dubbed items? [1,1,2,2,3,3]

Is there a method?

like image 778
Roberto Pezzali Avatar asked May 03 '26 09:05

Roberto Pezzali


2 Answers

Try this one

[1, 2, 3].flat_map { |i| [i, i] }
 => [1, 1, 2, 2, 3, 3] 
like image 177
Ursus Avatar answered May 04 '26 23:05

Ursus


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.

like image 41
Eric Duminil Avatar answered May 04 '26 23:05

Eric Duminil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!