在 Ruby 中合并和交错两个数组 [英] Merge and interleave two arrays in Ruby
本文介绍了在 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
这篇关于在 Ruby 中合并和交错两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文