在Ruby中合并和交错两个数组

我有以下代码:

a = ["Cat", "Dog", "Mouse"] s = ["and", "&"] 

我想将数组合并到数组a ,这会给我:

 ["Cat", "and", "Dog", "&", "Mouse"] 

通过Ruby数组和可枚举文档,我没有看到这样的方法,将实现这一点。

有没有一种方法,我可以做到这一点,而不是遍历每个数组?

你可以这样做:

 a.zip(s).flatten.compact 

这不会按照Chris要求的顺序给出结果数组,但是如果结果数组的顺序不重要,可以使用a |= b 。 如果你不想改变a ,你可以写a | b a | b并将结果分配给一个variables。

请参阅http://www.ruby-doc.org/core/classes/Array.html#M000275中有关Array类的set union文档。

这个答案假设你不想要重复的数组元素。 如果你想在你的最后一个数组中使用重复的元素, a += b可以做到这一点。 同样,如果你不想改变a ,使用a + b并将结果赋给一个variables。

作为对本页面的一些评论的回应,这两个解决scheme将适用于任何大小的数组。

如果你不想重复,为什么不使用联合运算符:

 new_array = a | s 
 s.inject(a, :<<) s #=> ["and", "&"] a #=> ["Cat", "Dog", "Mouse", "and", "&"] 

它不会给你所要求的顺序,但是通过追加到两个数组是很好的方式。

这是一个允许交错多个不同大小的数组(通用解决scheme)的解决scheme:

 arr = [["Cat", "Dog", "Mouse", "boo", "zoo"], ["and", "&"], ["hello", "there", "you"]] first, *rest = *arr; first.zip(*rest).flatten.compact => ["Cat", "and", "hello", "Dog", "&", "there", "Mouse", "you", "boo", "zoo"] 

它不完美,但它适用于任何大小的数组:

 >> a.map.with_index { |x, i| [x, i == a.size - 2 ? s.last : s.first] }.flatten[0..-2] #=> ["Cat", "and", "Dog", "&", "Mouse"] 

如果更通用的解决scheme,即使第一个数组不是最长的,并接受任何数量的数组呢?

 a = [ ["and", "&"], ["Cat", "Dog", "Mouse"] ] b = a.max_by(&:length) a -= [b] b.zip(*a).flatten.compact => ["Cat", "and", "Dog", "&", "Mouse"] 
 arr = [0, 1] arr + [2, 3, 4] //outputs [0, 1, 2, 3, 4]