How to get the nth element of an Enumerable in Ruby

后端 未结 4 776
甜味超标
甜味超标 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:51

    What about this?

    Prime.to_enum.with_index(1){|e, i| break e if i == 10000}
    # => 104729
    

    For enumerators that are not lazy, you probably want to put lazy on the enumerator.

提交回复
热议问题