2

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?

1

4 Answers 4

9

Try this one

[1, 2, 3].flat_map { |i| [i, i] }
 => [1, 1, 2, 2, 3, 3] 
Sign up to request clarification or add additional context in comments.

1 Comment

Or more generally: flat_map { |i| [ i ] * n } for n repetitions.
4

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.

Comments

3

@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]

4 Comments

A slight variation a.each_with_object([]) { |e,o| 2.times {o.push e} }
@sagarpandya82, thanks for the variation. There are too many possible variants, I prefer mine, it seems more readable :)
How would you modify the methods to accept an arbitrary number of repetitions?
@Eric, I added some comments. For the first example it's possible ( zip n times) but looks ugly and slow, let me know if you are still need this :)
-2

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] 

5 Comments

This is by far the most clean version
You're making some assumptions here. What happens if the array is [11, 6, 42, 23]?
@Ruslan: Nope. This answer might look clean, but it's wrong. What about [2,1] or [1,'2'] ?
One way around the sorting: ([1, '2'] * 2).sort {|x, y| x.to_s <=> y.to_s}
@muistooshort - Maybe you are the one making assumptions. Yes, there is a dearth of information in the question. But making stuff up and saying that is what they have in mind is definitely wrong. Continuing the conversation with Roberto would be good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.