I have 2 arrays:
['a', 'b', 'c', 'd', 'e', 'f']
['g', 'h', 'i']
I need to insert elements of second array after every second element (or nth) of the first array, resulting in:
['a', 'b', 'g', 'c', 'd', 'h', 'e', 'f', 'i']
Is there an easy way for me to do this?
You can always use a custom Enumerator:
a1 = ['a', 'b', 'c', 'd', 'e', 'f']
a2 = ['g', 'h', 'i']
enum = Enumerator.new do |y|
e1 = a1.each
e2 = a2.each
loop do
y << e1.next << e1.next << e2.next
end
end
enum.to_a #=> ["a", "b", "g", "c", "d", "h", "e", "f", "i"]
Or for the general case:
n.times { y << e1.next }
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