1

I have an array [1,2,3] and I want to insert the same value (true) between each item so that it becomes:

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

My current method is a little long-winded:

[1,2,3].zip(Array.new(3, true)).flatten

Can anyone suggest a more elegant way to do this?

2
  • 1
    What are going to do with this array after? Maybe there's an easier way to do that than going through a temp array. Commented Jul 31, 2019 at 13:16
  • 1
    Your text and your example do not match up. In your text, you say you want to insert a single value between items, whereas in your code example, you are adding a value after each item. Also, your question is confusing since you are asking about inserting a value between each item, which doesn't make sense, since you cannot insert something between one thing, you can only insert it between two things. Commented Jul 31, 2019 at 17:28

2 Answers 2

5

You can try using flat_map, and add after each element a true object:

p [1, 2, 3].flat_map { |e| [e, true] } # [1, true, 2, true, 3, true]

Another way would be to get the product of [1,2,3] and [true], and flatten the result:

p [1, 2, 3].product([true]).flatten # [1, true, 2, true, 3, true]
Sign up to request clarification or add additional context in comments.

Comments

3

Only a small tweak: Your code suffers from having to know the number of elements in the array being processed. This takes the form of the magic number 3 used to make the true array. Here is an alternative. Better? Dunno, but at least no magic numbers to break.

[1,2,3].zip([true].cycle).flatten

yields

[1, true, 2, true, 3, true]

Curious note: Adding a space between the "zip" and the opening "(" will cause the interpreter (version 2.3.3 in my tests) to generate an error:

Error NoMethodError: undefined method `flatten' for #<Enumerator: [true]:cycle>

This may be more robust as it avoids ambiguity in Ruby's "friendly" parser:

([1,2,3].zip([true].cycle)).flatten

Comments

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.