Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the nth element of an Enumerable in Ruby

Tags:

ruby

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?

like image 712
Stefan Avatar asked Jan 18 '16 11:01

Stefan


2 Answers

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
like image 130
Frederick Cheung Avatar answered Sep 23 '22 20:09

Frederick Cheung


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.

like image 30
sawa Avatar answered Sep 21 '22 20:09

sawa