“break” vs “raise StopIteration” in a Ruby Enumerator

☆樱花仙子☆ 提交于 2019-12-11 04:44:15

问题


If I use Ruby Enumerators to implement a generator and a filter:

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

does it make any difference whether I break out of the generator's loop using

break if x > CUTOFF

vs

raise StopIteration if x > CUTOFF

?

Both seem to work. I imagine break would be more performant, but is raise more idiomatic here?


回答1:


In Ruby it's considered a bad practice to use raise/fail for control flow as they are really slow.

So to answer your question raise StopIteration if x > CUTOFF isn't an idiomatic way of breaking from the loop



来源:https://stackoverflow.com/questions/41173039/break-vs-raise-stopiteration-in-a-ruby-enumerator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!