ruby 中的 break 和 return,你如何使用它们? [英] break and return in ruby, how do you use them?

查看:14
本文介绍了ruby 中的 break 和 return,你如何使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚问了一个关于退货的问题似乎和break一样.你如何使用return,你如何使用break,例如在你编写的实际代码中,以解决可以使用这些构造的问题.

I just asked a question about return and it seems to do the same thing as break. How do you use return, and how do you use break, such as in the actual code that you write to solve the problems that can use these constructs.

我不能真正发布示例,因为我不知道如何使用这些示例,所以它们没有多大意义.

I can't really post examples because I don't know how to use these so they wouldn't make much sense.

推荐答案

return 退出整个函数.

Return exits from the entire function.

Break 从最里面的循环退出.

Break exits from the innermost loop.

因此,在这样的函数中:

Thus, in a function like so:

def testing(target, method)
  (0..100).each do |x|
    (0..100).each do |y|
     puts x*y
     if x*y == target
       break if method == "break"
       return if method == "return"
     end
    end 
  end
end

要查看差异,请尝试:

testing(50, "break")
testing(50, "return")

这篇关于ruby 中的 break 和 return,你如何使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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