user3574603
user3574603

Reputation: 3618

Ruby: How can I insert a single value between each item in an array?

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?

Upvotes: 1

Views: 1002

Answers (2)

Peter Camilleri
Peter Camilleri

Reputation: 1912

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

Upvotes: 2

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

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]

Upvotes: 5

Related Questions