从外部方法调用接下来的ruby循环
发布时间:2020-12-17 01:21:23 所属栏目:百科 来源:网络整理
导读:在 Ruby中,很容易告诉循环去下一个项目 (1..10).each do |a| next if a.even? puts aend result = 13 579 但是如果我需要从循环外调用next(例如:method) def my_complex_method(item) next if item.even? # this will obviously fail end(1..10).each do |a
在
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 我发现和工作的唯一解决方案是使用throw&抓住像在这个问题How to break outer cycle in 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 我的问题是:任何人有更多的解决方案呢?或者是扔/捕捉只有这样做吗? 另外如果我想调用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 一个简单的方法,但不同于尝试一个. UPDATE 作为item.even?已经返回一个布尔值,如果item.even不需要true部分,你可以做如下: def my_complex_method(item) item.even? end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |