我可以将两个大小相等的数组合并为一个带有合并值子数组的数组吗? [英] Can I merge two equally sized arrays into one array with sub-arrays of merged values?

查看:29
本文介绍了我可以将两个大小相等的数组合并为一个带有合并值子数组的数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

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"]]

这篇关于我可以将两个大小相等的数组合并为一个带有合并值子数组的数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆