我想取通过块的前n个条目。
我希望在得到 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