Ruby枚举:获取满足块条件的前n个元素

3
我想取通过块的前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

我觉得你的解决方案似乎会选择一些 x 值,即使 x.expensive_operation? 为 false... 这是你想要的吗? - Baldrick
嗯...你说的没错,我的解决方案似乎不对,但不是你所提出的那种方式。它将在第一个 expensive_operation 为 false 的值处停止,并返回少于 n 个值。 - Aditya Sanghi
2个回答

5

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

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

1

它应该可以通过一个简单的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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接