结合两个数组来创建一个二维数组在ruby。

时间:2021-10-09 12:54:16
a = [1, 2, 3]
b = [4, 5, 6]

How would I combine the two arrays in a 2D array?:

如何在二维数组中组合这两个数组?

[[1, 4], [2, 5], [3, 6]]

2 个解决方案

#1


30  

Try Array#zip

尝试数组#拉链

a.zip(b)
=> [[1,4],[2,5],[3,6]]

#2


10  

While zip is obviously the most straightforward answer, this also works:

虽然zip显然是最直接的答案,但它也适用:

[a, b].transpose
=> [[1, 4], [2, 5], [3, 6]]

#1


30  

Try Array#zip

尝试数组#拉链

a.zip(b)
=> [[1,4],[2,5],[3,6]]

#2


10  

While zip is obviously the most straightforward answer, this also works:

虽然zip显然是最直接的答案,但它也适用:

[a, b].transpose
=> [[1, 4], [2, 5], [3, 6]]