我可以将两个大小相等的数组合并为一个带有合并值子数组的数组吗?

问题描述:

我有两个数组:

a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]

我想得到一个看起来像这样的数组:

I would like to get an array that looks like:

combined = [["a1", "b1"], ["a2", "b2"], ["a3", "b3"]]

我在带有 Hash [a.zip b] 的哈希中找到了解决方案,该哈希返回:

I found the solution in a Hash with Hash[a.zip b] which returns:

{"a1"=>"b1", "a2"=>"b2", "a3"=>"b3"}

这可能必须使用lambda函数来解决,但是我想知道是否有一些快速的Ruby魔术使它成为了一个均匀的单行代码.

This may have to be solved with a lambda function, but I was wondering if there was some quick Ruby magic which made this an even-quicker one-liner.

我不确定为什么要使用 Hash . Array#zip 是您需要的方法.

I'm not sure why you have Hash involved. Array#zip is the method you need.

a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]

a.zip(b) # => [["a1", "b1"], ["a2", "b2"], ["a3", "b3"]]