"break" vs Ruby 枚举器中的"raise StopIteration"



如果我使用 Ruby 枚举器来实现生成器和过滤器:

generator = Enumerator.new do |y|
x = 0
loop do
y << x
x += 1
break if x > CUTOFF
end
end.lazy
filter = Enumerator.new do |y|
loop do
i = generator.next
y << i if i.even?
end
end

我是否

使用
break if x > CUTOFF

raise StopIteration if x > CUTOFF

两者似乎都有效。我想break会更有表现,但这里的raise更惯用吗?

在 Ruby 中,使用raise/fail进行控制流被认为是一种不好的做法,因为它们真的很慢。

所以回答你的问题raise StopIteration if x > CUTOFF不是打破循环的惯用方式

最新更新