将数组插入另一个数组的第 n 个元素 [英] Inserting an array into every nth element of another
本文介绍了将数组插入另一个数组的第 n 个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 2 个数组:
['a', 'b', 'c', 'd', 'e', 'f']
['g', 'h', 'i']
我需要在第一个数组的每第二个元素(或第 n 个)之后插入第二个数组的元素,结果:
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?
推荐答案
您始终可以使用自定义的 Enumerator
:
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"]
或者对于一般情况:
n.times { y << e1.next }
这篇关于将数组插入另一个数组的第 n 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文