Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an array into every nth element of another

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?

like image 774
Mark Avatar asked Dec 03 '25 13:12

Mark


1 Answers

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 }
like image 50
Stefan Avatar answered Dec 05 '25 02:12

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!