B Seven B Seven - 1 month ago 5x
Ruby Question

What is a good way to select and take in Ruby?

Suppose you have a list of 1,000 items and want to select 10. The condition for select is expensive, but the chance of selecting is high (say 99%).

list.select do |item|
item if is_ok?(item)

This code is very inefficient because it checks each item, when it need rarely check more than 10.

What is a better, more efficient and Rubyish way of doing it?


With lazy enumerators:

list2 = list.lazy.select { |item| is_ok?(item) }.take(10) # .to_a to get an array

As per @tadman comment, let me emphasize that .select { |x| x if p(x) } is redundant, in a filter you use only the predicate: select { |x| p(x) }.