在 Ruby 中合并和交错两个数组
问题描述:
我有以下代码:
a = ["Cat", "Dog", "Mouse"]
s = ["and", "&"]
我想将数组 s
合并到数组 a
中,这会给我:
I want to merge the array s
into array a
which would give me:
["Cat", "and", "Dog", "&", "Mouse"]
查看 Ruby Array 和 Enumerable 文档,我没有看到可以实现此目的的方法.
Looking through the Ruby Array and Enumerable docs, I don't see such a method that will accomplish this.
有没有一种方法可以在不遍历每个数组的情况下做到这一点?
Is there a way I can do this without iterating through each array?
答
你可以这样做:
a.zip(s).flatten.compact