按特定顺序组合两个数组

时间:2017-11-14 04:12:44

标签: arrays ruby

我需要结合这两个数组:

A = ["Dog", "Cat", "Bird"]
B = ["John", "Doe", "Foo"]

我必须获取第一个数组的第一个元素,然后是第二个数组的第一个元素,然后是第一个数组的第二个元素和第二个数组的第二个元素,依此类推。它必须按照这个确切的顺序:

["Dog", "John", "Cat", "Doe", "Bird", "Foo"]

2 个答案:

答案 0 :(得分:7)

您可以使用Array#zip获取[[A[0], B[0]], [A[1], B[1]], ...]

A.zip(B)
# => [["Dog", "John"], ["Cat", "Doe"], ["Bird", "Foo"]]

展平它会给你你想要的东西:

A.zip(B).flatten
# => ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]
使用Enumerable#flat_map

更新替代方案

(0...A.size).map { |i| [A[i], B[i]] }
# => [["Dog", "John"], ["Cat", "Doe"], ["Bird", "Foo"]]
(0...A.size).flat_map { |i| [A[i], B[i]] }
# => ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]

答案 1 :(得分:0)

let g:ycm_autoclose_preview_window_after_completion=1