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.
Given that Ruby is such an elegant language, I would have expected something like:
Prime.at(9999) #=> 104729
But there is no Enumerable#at
.
Is the above workaround intended or is there a more direct way to get the nth element of an Enumerable
?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With