Specify the counter value with the specified index

Suppose I have an enumerated object enum, and now I want to get the third element.

I know that one of the common approaches is to convert to an array and then access with an index, for example:

enum.to_a[2]

But this method will create a temporary array, and it can be inefficient.

Now I use:

enum.each_with_index {|v, i| break v if i == 2}

But this is pretty ugly and redundant.

What is the most efficient way to do this?

+5
source share
3 answers

You can use taketo clear the first three elements, and then lastto grab the third element from the array, which takegives you:

third = enum.take(3).last

If you do not want to generate any arrays at all, then it is possible:

# If enum isn't an Enumerator then 'enum = enum.to_enum' or 'enum = enum.each'
# to make it one.
(3 - 1).times { enum.next }
third = enum.next
+5
source

mu enumerable-lazy Ruby 2.1. , next, :

enum.lazy.drop(2).first
+5

Unfortunately, to access a member by index, it must be converted to an array (otherwise you would not have an index in the first place), so your code looks great to me.

+1
source

All Articles