且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Ruby中使用索引进行映射?

更新时间:2023-01-23 08:13:43

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

If you're using ruby 1.8.7 or 1.9, you can use the fact that iterator methods like each_with_index, when called without a block, return an Enumerator object, which you can call Enumerable methods like map on. So you can do:

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

在 1.8.6 中你可以这样做:

In 1.8.6 you can do:

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