Lets say I have this:
让我说我有这个:
a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
c = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']
And I want this:
我想要这个:
d = [[1, 'a', 'ABC'], [2, 'b', 'DEF'], ...]
How can I accomplish this in Ruby?
我怎样才能在Ruby中实现这一目标?
I tried with .zip
我试过.zip
r = []
r.zip(a, b, c)
puts r
But didn't work.
但没有奏效。
3 个解决方案
#1
2
You need to do as below :-
你需要做如下: -
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"]]
One thing to remember here - Array#zip
returns an array of size, equal to the size of the receiver array object.
这里要记住的一件事 - Array#zip返回一个大小的数组,等于接收器数组对象的大小。
# 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]) # => []
For the same reason as I explained above r.zip(a, b, c)
returns []
.
出于与上面解释的相同的原因,r.zip(a,b,c)返回[]。
#2
1
[a,b,c].reduce(:zip).map(&:flatten)
#3
0
d = [a,b,c].transpose
[[1, "a", "ABC"], [2, "b", "DEF"], [3, "c", "GHI"], [4, "d", "JKL"], [5, "e", "MNO"]]
#1
2
You need to do as below :-
你需要做如下: -
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"]]
One thing to remember here - Array#zip
returns an array of size, equal to the size of the receiver array object.
这里要记住的一件事 - Array#zip返回一个大小的数组,等于接收器数组对象的大小。
# 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]) # => []
For the same reason as I explained above r.zip(a, b, c)
returns []
.
出于与上面解释的相同的原因,r.zip(a,b,c)返回[]。
#2
1
[a,b,c].reduce(:zip).map(&:flatten)
#3
0
d = [a,b,c].transpose
[[1, "a", "ABC"], [2, "b", "DEF"], [3, "c", "GHI"], [4, "d", "JKL"], [5, "e", "MNO"]]