Ruby枚举器中的“break”vs“raise StopIteration”

如果我使用Ruby Enumerators来实现生成器和filter:

generator = Enumerator.new do |y| x = 0 loop do y < 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 

VS

 raise StopIteration if x > CUTOFF 

两者似乎都有效。 我想break会更有效率,但在这里raise更多的惯用语?

在Ruby中,对控制流使用raise/fail 失是一种不好的做法 ,因为它们非常慢。

所以要回答你的问题, raise StopIteration if x > CUTOFF不是从循环中断开的惯用方法,请raise StopIteration if x > CUTOFF