Ogrish Man Ogrish Man - 3 months ago 14
Ruby Question

How to insert a new element in between all elements of a Ruby array?

I have an Array and want to insert a new element in between all elements, someway like the

join
method. For example, I have

[1, [], "333"]


and what I need is

[1, {}, [], {}, "333"]


Note a new empty hash was inserted in between all elements.

Edit:
Currently what I have is:

irb(main):028:0> a = [1, [], "333"]
=> [1, [], "333"]
irb(main):029:0> a = a.inject([]){|x, y| x << y; x << {}; x}
=> [1, {}, [], {}, "333", {}]
irb(main):030:0> a.pop
=> {}
irb(main):031:0> a
=> [1, {}, [], {}, "333"]
irb(main):032:0>


I want to know the best way.

Answer
[1, 2, 3].flat_map { |x| [x, :a] }[0...-1]
#=> [1, :a, 2, :a, 3]

FYI, that function is called intersperse (at least in Haskell).

[Update] If you want to avoid the slice (that created a copy of the array):

[1, 2, 3].flat_map { |x| [x, :a] }.tap(&:pop)
#=> [1, :a, 2, :a, 3]
Comments