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
4

2 回答 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]
于 2012-10-28T11:46:54.227 回答
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
于 2012-10-28T13:55:11.920 回答