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.
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() .
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, 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With