如果我使用 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
不是打破循环的惯用方式