Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refer an enumerator value with specified index

Assume I have an enumerable object enum and now I want to get the third item.

I know one of a general approach is convert into an array and then access with index like:

enum.to_a[2]

But this way will create a temporary array and it might be inefficient.

Now I use:

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

But this is quite ugly and redundant.

What's the most efficient way to do this?

like image 804
Shou Ya Avatar asked Jun 11 '12 01:06

Shou Ya


2 Answers

You could use take to peel off the first three elements and then last to grab the third element from the array that take gives you:

third = enum.take(3).last

If you don't want to generate any arrays at all then perhaps:

# 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
like image 99
mu is too short Avatar answered Sep 21 '22 06:09

mu is too short


Alternative to mu's answer using enumerable-lazy or Ruby 2.1. As lazy as using next but much more declarative:

enum.lazy.drop(2).first
like image 33
tokland Avatar answered Sep 19 '22 06:09

tokland