davidhu2000 davidhu2000 - 6 months ago 19
Ruby Question

Ruby select method: check number of items that are selected

So, Ruby has a select method that can pick the elements from an array based on conditions passed in from a block.

For example

arr = [1,2,3,4]
arr.select {|x| x.even? } => [2, 4]

My problem deals with a large array, and I only want a certain number of items selected. For example, out of the array, I only want the first 5 numbers that matches the condition.

arr.select{|x| x.even?}[0...5]

This is what I have so far. This is extremely slow because Ruby runs the select function on the entire array before picking the first five element.

I want to see if there is a way to stop the select function when the first five elements are selected.

For example, if I can do this

res = arr.select do |x|
break if self.length > 5

In this case, self is a reference to the res array. I don't think that reference will work, but I hope it gets my point across.


In this case, self is a reference to the res array.

The keyword self in Ruby gives you access to the current object – the object that is receiving the current message.

I think it is a job for Enumerator::Lazy:

>> (1..100000).lazy.select { |x| x.even? }.first(5)
=> [2, 4, 6, 8, 10]