Inserting an array into every nth element of another

前端 未结 3 632
梦毁少年i
梦毁少年i 2021-01-14 19:27

I have 2 arrays:

[\'a\', \'b\', \'c\', \'d\', \'e\', \'f\']
[\'g\', \'h\', \'i\']

I need to insert elements of second array after every sec

3条回答
  •  鱼传尺愫
    2021-01-14 20:03

    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 }
    

提交回复
热议问题