在Ruby中,很容易告诉循环转到下一个项目
(1..10).each do |a|
next if a.even?
puts a
end
结果=>
1
3
5
7
9
但是,如果我需要从循环外部调用下一步(例如:方法),该怎么办?
def my_complex_method(item)
next if item.even? # this will obviously fail
end
(1..10).each do |a|
my_complex_method(a)
puts a
end
我发现并工作的唯一解决方案是在SO问题中使用throw
&catch
like如何打破Ruby中的外部循环?
def my_complex_method(item)
throw(:skip) if item.even?
end
(1..10).each do |a|
catch(:skip) do
my_complex_method(a)
puts a
end
end
我的问题是:任何人都可以通过更多的解决方案来解决此问题?或throw/catch
唯一的方式做到这一点?
还有,如果我my_complex_method
不仅要在该循环的一部分中调用(=>不要抛出:skip),我还能以某种方式告诉我从循环中调用它的方法吗?
您的复杂方法可能返回一个布尔值,然后像这样在循环中进行比较:
def my_complex_method(item)
true if item.even?
end
(1..10).each do |a|
next if my_complex_method(a)
puts a
end
一种简单的方法,但与尝试捕获方法不同。
更新
由于item.even?
已经返回了布尔值,因此不需要该true if item.even?
部分,可以执行以下操作:
def my_complex_method(item)
item.even?
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句