How to get the nth element of an Enumerable in Ruby

后端 未结 4 773
甜味超标
甜味超标 2021-01-18 11:20

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

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

But creating a huge

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-18 11:50

    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
    

提交回复
热议问题