Roberto Pezzali
Roberto Pezzali

Reputation: 2494

Duplicate elements of array in 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?

Upvotes: 2

Views: 1147

Answers (4)

Ilya
Ilya

Reputation: 13477

@Ursus answer is the most clean, there are possible solutions:

a = [1, 2, 3]
a.zip(a).flatten
#=> [1, 1, 2, 2, 3, 3]

Or

a.inject([]) {|a, e| a << e << e} #  a.inject([]) {|a, e| n.times {a << e}; a}
=> [1, 1, 2, 2, 3, 3]

Or

[a, a].transpose.flatten # ([a] * n).transpose.flatten
=> [1, 1, 2, 2, 3, 3]

Upvotes: 3

Eric Duminil
Eric Duminil

Reputation: 54223

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.

Upvotes: 4

seph
seph

Reputation: 6076

Try this:

[1, 2, 3] * 2

 => [1, 2, 3, 1, 2, 3] 

You might want it sorted:

([1, 2, 3] * 2).sort

 => [1, 1, 2, 2, 3, 3] 

Upvotes: -2

Ursus
Ursus

Reputation: 30056

Try this one

[1, 2, 3].flat_map { |i| [i, i] }
 => [1, 1, 2, 2, 3, 3] 

Upvotes: 9

Related Questions