Inserting an array into every nth element of another

前端 未结 3 633
梦毁少年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 19:52
    a=['a', 'b', 'c', 'd', 'e', 'f']
    b=['g', 'h', 'i']
    b.each.with_index(1) { |e,i| a.insert((3*i)-1,e) }
    
    a
    #=> ['a', 'b', 'g', 'c', 'd', 'h', 'e', 'f', 'i']
    
    0 讨论(0)
  • 2021-01-14 20:00

    Something like this:

    a = ['a', 'b', 'c', 'd', 'e', 'f']
    b = ['g', 'h', 'i']
    a.each_slice(2). # => [["a", "b"], ["c", "d"], ["e", "f"]]
      zip(b). # => [[["a", "b"], "g"], [["c", "d"], "h"], [["e", "f"], "i"]]
      flatten # => ['a', 'b', 'g', 'c', 'd', 'h', 'e', 'f', 'i']
    
    0 讨论(0)
  • 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 }
    
    0 讨论(0)
提交回复
热议问题