gpt4 book ai didi

ruby - 如何在 Ruby 中使用索引进行映射/收集?

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:11 25 4
gpt4 key购买 nike

什么是最简单的转换方式

[x1, x2, x3, ... , xN]

[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]

最佳答案

如果您使用的是 ruby​​ 1.8.7 或 1.9,您可以使用迭代器方法,如 each_with_index,在没有 block 的情况下调用时,返回一个 Enumerator 对象,您可以调用 Enumerable 方法,例如 map。所以你可以这样做:

arr.each_with_index.map { |x,i| [x, i+2] }

在 1.8.6 中你可以:

require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }

关于ruby - 如何在 Ruby 中使用索引进行映射/收集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4697557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com