5

I have an array rangers = ["red", "blue", "yellow", "pink", "black"] (it's debatable that green should part of it, but I decided to omitted it)

I want to double the array elements so it returns rangers = ["red", "red", "blue", "blue", "yellow", "yellow", "pink", "pink", "black", "black"] in that order.

I tried look around SO, but I could not find find a way to do it in that order. (rangers *= 2 won't work).

I have also tried rangers.map{|ar| ar * 2} #=> ["redred", "blueblue",...]

I tried rangers << rangers #=> ["red", "blue", "yellow", "pink", "black", [...]]

How can I duplicate elements to return the duplicate element value right next to it? Also, if possible, I would like to duplicate it n times, so when n = 3, it returns ["red", "red", "red", "blue", "blue", "blue", ...]

1
  • 1
    The green ranger is the best one, though. ;P Commented Jul 25, 2016 at 18:34

1 Answer 1

9

How about

rangers.zip(rangers).flatten

using Array#zip and Array#flatten?

A solution that might generalize a bit better for your second request might be:

rangers.flat_map { |ranger| [ranger] * 2 }

using Enumerable#flat_map. Here you can just replace the 2 with any value or variable.

Sign up to request clarification or add additional context in comments.

6 Comments

also: ([rangers]*n).inject(&:zip).flatten :)
Oh, very nice @MladenJablanović. ;)
Very convenient! I didn't think of using zip + flatten combo. Will prove very handy in the future. Thanks all!
@MladenJablanović even better in my opinion though: ([rangers] * n).transpose.flatten. This question really inspires me. x)
This card allows you to go directly to flat_map without passing map (I.e. no reason to mention map).
|

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.