我有以下代码:
a = ["Cat", "Dog", "Mouse"]
s = ["and", "&"]
我想将数组s
合并到数组a
中,这将给我:
["Cat", "and", "Dog", "&", "Mouse"]
查看 Ruby 数组和 Enumerable 文档,我没有找到可以完成这个任务的方法。
有没有一种方法可以不通过遍历每个数组来实现这个目标?
a.zip(s).flatten.compact
a
具有超过 3 个元素,会怎样? - Michael Kohl[a, s].transpose
,但两行不符合要求,所以#zip
是显而易见的解决方案。我认为他并不在意a
是否被改变……我不认为他在评论可变vs函数式解决方案,他只是试图描述这种模式。 - DigitalRoss这种方法不能按照Chris的要求给出一个结果数组,但是如果结果数组的顺序不重要,你可以使用a |= b
。如果你不想改变a
,你可以写成a | b
并将结果赋值给一个变量。
请参阅Array类的集合并文档。
此答案假设您不希望在最终数组中包含重复元素。如果您允许在最终数组中包含重复元素,则a += b
应该可以解决问题。同样,如果您不想改变a
,请使用a + b
并将结果赋值给一个变量。
针对本页面的一些评论,这两个解决方案适用于任何大小的数组。
["猫", "狗", "老鼠", "和", "&"]
,这不是原作者想要的。 - Andrew Grimm如果你不想要重复的元素,为什么不使用 并集运算符 呢:
new_array = a | s
s
的结果将位于新数组的末尾。 - Hendriks.inject(a, :<<)
s #=> ["and", "&"]
a #=> ["Cat", "Dog", "Mouse", "and", "&"]
它不会按照你所请求的顺序给出结果,但它是一种很好的合并两个数组的方式,通过将一个数组追加到另一个数组后面。
a | s
那样简短和干净。 - Harry Woodarr = [["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"]
i = s.cycle; a.map { |x| [x, i.next] }.flatten[0..-2]
也同样有效。 - mu is too shortand
和 &
,因此我尽可能地按照字面意思理解,同时允许任意长度的 a
。 - Michael Kohla
和 s
大小不同的情况:a.zip(s).flatten.compact | s
.compact
将在a
大于s
时删除nil
| s
将在a
小于s
时添加s
中剩余的项目a = [
["and", "&"],
["Cat", "Dog", "Mouse"]
]
b = a.max_by(&:length)
a -= [b]
b.zip(*a).flatten.compact
=> ["Cat", "and", "Dog", "&", "Mouse"]
一种实现交错操作并保证其中一个数组是zip方法中最大的数组的方法是,将其中一个数组填充为nil
,直到其大小与另一个数组相同。这样,您还可以保证哪个数组的哪个元素将位于第一个位置:
preferred_arr = ["Cat", "Dog", "Mouse"]
other_arr = ["and","&","are","great","friends"]
preferred_arr << nil while preferred_arr.length < other_arr.length
preferred_arr.zip(other_arr).flatten.compact
#=> ["Cat", "and", "Dog", "&", "Mouse", "are", "great", "friends"]
preferred_arr.zip(other_arr).flatten | other_arr
(不需要填充 nil 值) - Adam Fendleya = ["Cat", "Dog", "Mouse"]
s = ["and", "&"]
[*a, *s]
#=> ["Cat", "Dog", "Mouse", "and", "&"]