Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

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.

like image 821
Just a learner Avatar asked Feb 23 '12 22:02

Just a learner


People also ask

How do you add an element to an array between?

concat(Array, element); When you want to add an element to the end of your array, use push() . If you need to add an element to the beginning of your array, use unshift() . If you want to add an element to a particular location of your array, use splice() .

Can we add element in middle of array?

We can insert the elements wherever we want, which means we can insert either at starting position or at the middle or at last or anywhere in the array.


1 Answers

[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]
like image 194
tokland Avatar answered Sep 20 '22 15:09

tokland