如果我使用 Ruby Enumerators 来实现生成器和过滤器:
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
vs
raise StopIteration if x > CUTOFF
?
两者似乎都有效。我想break
会更高效,但是raise
这里更惯用吗?
在红宝石中是被认为是不好的做法 https://github.com/bbatsov/ruby-style-guide#no-exceptional-flows to use raise/fail
用于控制流,因为它们真的很慢。
所以回答你的问题raise StopIteration if x > CUTOFF
不是打破循环的惯用方式
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)