从外部方法调用 ruby​​ 循环的 next [英] call next on ruby loop from external method

查看:35
本文介绍了从外部方法调用 ruby​​ 循环的 next的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

in Ruby it's easy to tell loop to go to next item

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

结果 =>

1
3   
5
7
9

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

but what if I need to call next from outside of the loop (e.g.: 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 &catch 就像 SO 问题 如何打破外循环红宝石?

only solution I found and works is to use throw & catch like in SO question 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

我的问题是:有人有更漂亮的解决方案来做到这一点吗??还是 throw/catch 唯一的方法??

My question is: anyone got any more niftier solution to do this ?? or is throw/catch only way to do this ??

还有什么如果我想调用 my_complex_method 不仅作为该循环的一部分(=> 不要抛出 :skip),我能以某种方式告诉我的方法它是从循环中调用的吗?

Also what If I want to call my_complex_method not only as a part of that loop (=> don't throw :skip) , can I somehow tell my method it's called from a loop ?

推荐答案

您的复杂方法可以返回一个布尔值,然后您可以像这样在循环中进行比较:

You complex method could return a boolean, and then you compare on your loop like this:

def my_complex_method(item)
  true if item.even? 
end

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

一种简单的方法,但与 try catch 不同.

A simple approach, but different from the try catch one.

更新

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

As item.even? already return a boolean value, you don't need the true if item.even? part, you can do as follow:

def my_complex_method(item)
  item.even? 
end

这篇关于从外部方法调用 ruby​​ 循环的 next的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆