Ruby枚举:首先采用了块返回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条目后进行短路迭代。

您建议什么?在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
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

最新更新