How to get the nth element of an Enumerable in Ruby

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

    Based on sawa's solution, here's a more succinct alternative:

    Prime.find.with_index(1) { |_, i| i == 10000 }
    #=> 104729
    

    or

    Prime.find.with_index { |_, i| i == 9999 }
    #=> 104723
    

提交回复
热议问题