Ruby Enumeration:首先取n,其中block返回true

我想获取通过块的第一个“n”条目

a = 1..100_000_000 # Basically a long array # This iterates over the whole array -- no good b = a.select{|x| x.expensive_operation?}.take(n) 

一旦我得到“昂贵”条件为真的n个条目,我想要将迭代短路。

你有什么建议? take_while并保持n的计数?

 # This is the code i have; which i think can be written better, but how? a = 1..100_000_000 # Basically a long array n = 20 i = 0 b = a.take_while do |x| ((i < n) && (x.expensive_operation?)).tap do |r| i += 1 end end 

Ruby 2.0实现了懒惰的枚举 ,对于旧版本,使用gem enumerable-lazy :

 require 'enumerable/lazy' (1..Float::INFINITY).lazy.select(&:even?).take(5).to_a #=> [2, 4, 6, 8, 10] 

它应该使用简单的for循环和break

 a = 1..100_000_000 # Basically a long array n = 20 selected = [] for x in a selected << x if x.expensive_operation? break if select.length == n end