如何在Ruby中使用索引进行映射? [英] How to map with index in Ruby?
本文介绍了如何在Ruby中使用索引进行映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最简单的转换方法是什么
What is the easiest way to convert
[x1, x2, x3, ... , xN]
到
[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]
推荐答案
如果您使用的是 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] }
这篇关于如何在Ruby中使用索引进行映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文