从外部方法调用ruby循环上的next

在Ruby中,很容易告诉循环转到下一个项目

(1..10).each do |a| next if a.even? puts a end 

result =>

 1 3 5 7 9 

但是如果我需要从循环外部调用next(例如:method)怎么办?

 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问题中使用throwcatch 如何打破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不仅作为该循环的一部分(=>不抛出:跳过),我能以某种方式告诉我的方法它是从循环中调用的吗?

你复杂的方法可以返回一个布尔值,然后你在你的循环上进行比较,如下所示:

 def my_complex_method(item) true if item.even? end (1..10).each do |a| next if my_complex_method(a) puts a end 

一个简单的方法,但不同于尝试捕获一个。

UPDATE

作为item.even? 已经返回一个布尔值,你不需要true if item.even? 部分,你可以这样做:

 def my_complex_method(item) item.even? end 

Enumerator#nextEnumerator#peek将是goo的好选择:

 def my_complex_method(e) return if e.peek.even? p e.peek end enum = (1..5).each enum.size.times do |a| my_complex_method(enum) enum.next end 

产量

 1 3 5 

如果您只需要对某些值执行操作,则根据my_complex_method返回的值,您可以明智地使用枚举器:

 (1..10).map { |a| [a, my_complex_method(a)] }.each do |a, success| puts a if success end 

您可以定义方法接受块并根据成功或失败在此块中执行一些操作:(1..10).each do | a | my_complex_method {|成功| 接下来如果成功}结束由于范围界定,你不能使用`catch` /`throw`,并根据处理状态调用`next`。