【问题标题】:Merge items of two arrays into new array [duplicate]将两个数组的项目合并到新数组中[重复]
【发布时间】:2017-11-02 22:54:34
【问题描述】:

我正在浏览 ruby​​ Array iterators。而且我找不到我要找的东西,而且我认为它已经存在:

我有两个数组:

["a", "b", "c"]

[0,1,2]

我想这样合并:

[ [0, "a"], [1, "b"], [2, "c"] ]

我认为迭代器存在于标准库中(我之前使用过),但我找不到它的名称。

【问题讨论】:

标签: ruby


【解决方案1】:

这应该可行:

[0,1,2].zip(["a", "b", "c"])        # => [[0, "a"], [1, "b"], [2, "c"]]

来自Array#zip函数的官方文档:

将任何参数转换为数组,然后将 self 的元素与每个参数的相应元素合并。

这会生成一系列 ary.size n 元素数组,其中 n 比参数的数量大一。

有关更多信息和其他示例,请参阅:

https://ruby-doc.org/core-2.4.2/Array.html#method-i-zip

【讨论】:

    【解决方案2】:

    您正在寻找 zip 功能

    https://apidock.com/ruby/Array/zip

    【讨论】:

      【解决方案3】:

      我认为你可以使用https://apidock.com/ruby/Enumerator/each_with_index 看到这个帖子difference between each.with_index and each_with_index in Ruby?

      或者,如果您有特定的值并且想要映射它们,您可以使用 map 或 zip。它在这篇文章中很好地解释了它 Combine two Arrays into Hash

      【讨论】:

        猜你喜欢
        • 2017-03-22
        • 1970-01-01
        • 2013-11-17
        • 2012-11-08
        • 2017-06-22
        • 1970-01-01
        • 2013-11-08
        • 1970-01-01
        • 2011-06-09
        相关资源
        最近更新 更多