在Ruby中加入多个有序数组

时间:2014-06-12 19:27:47

标签: ruby arrays

让我说我有这个:

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
c = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']

我想要这个:

d = [[1, 'a', 'ABC'], [2, 'b', 'DEF'], ...]

我如何在Ruby中实现这一目标?

我尝试了.zip

r = []
r.zip(a, b, c)
puts r

但没效果。

3 个答案:

答案 0 :(得分:2)

您需要执行以下操作: -

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
c = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']

a.zip(b,c) 
# => [[1, "a", "ABC"], [2, "b", "DEF"], [3, "c", "GHI"], [4, "d", "JKL"], [5, "e", "MNO"]]

要记住的一件事 - Array#zip返回 size 的数组,等于接收器数组对象的大小

# returns an array of size 2, as the same as receiver array size.
[1,2].zip([1,5,7]) # => [[1, 1], [2, 5]]
# below returns empty array, as the receiver array object is also empty.
[].zip([1,2,3,4,5]) # => []

出于与我上面解释的相同的原因r.zip(a, b, c)返回[]

答案 1 :(得分:1)

[a,b,c].reduce(:zip).map(&:flatten)

答案 2 :(得分:0)

d = [a,b,c].transpose
[[1, "a", "ABC"], [2, "b", "DEF"], [3, "c", "GHI"], [4, "d", "JKL"], [5, "e", "MNO"]]