如何在Ruby中获取Enumerable的第n个元素 [英] How to get the nth element of an Enumerable in Ruby

查看:42
本文介绍了如何在Ruby中获取Enumerable的第n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,要返回我可以写的第 10,000 个质数:

For example, to return the 10,000th prime number I could write:

require 'prime'
Prime.first(10000).last #=> 104729

但是创建一个巨大的中间数组,只是为了检索它的最后一个元素感觉有点麻烦.

But creating a huge intermediate array, just to retrieve its last element feels a bit cumbersome.

鉴于 Ruby 是一门如此优雅的语言,我会期待这样的:

Given that Ruby is such an elegant language, I would have expected something like:

Prime.at(9999) #=> 104729

但是没有Enumerable#at.

上述解决方法是打算还是有更直接的方法来获取 Enumerablenth 个元素?

Is the above workaround intended or is there a more direct way to get the nth element of an Enumerable?

推荐答案

我能想到的最接近假设的 at 方法是 drop,它跳过指定的元素的数量.它试图返回一个实际的数组,所以如果你使用无限序列,你需要将它与惰性结合起来,例如

The closest thing I can think of to a hypothetical at method is drop, which skips the indicated number of elements. It tries to return an actual array though so you need to combine it with lazy if you are using with infinite sequences, e.g.

Prime.lazy.drop(9999).first

这篇关于如何在Ruby中获取Enumerable的第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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