我怎样才能从一个街区提前归还一些东西? [英] How can I return something early from a block?

查看:25
本文介绍了我怎样才能从一个街区提前归还一些东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想做这样的事情:

If I wanted to do something like this:

collection.each do |i|
   return nil if i == 3

   ..many lines of code here..
end

我将如何获得这种效果?我知道我可以用一个大的 if 语句将块内的所有内容包装起来,但我想尽可能避免嵌套.

How would I get that effect? I know I could just wrap everything inside the block in a big if statement, but I'd like to avoid the nesting if possible.

Break 在这里不起作用,因为我确实想停止剩余元素的迭代.

Break would not work here, because I do not want to stop iteration of the remaining elements.

推荐答案

next 块内从块返回.块内的 break 从产生块的函数返回.对于 each 这意味着 break 退出循环并且 next 跳转到循环的下一个迭代(因此名称).您可以使用 next valuebreak value 返回值.

next inside a block returns from the block. break inside a block returns from the function that yielded to the block. For each this means that break exits the loop and next jumps to the next iteration of the loop (thus the names). You can return values with next value and break value.

这篇关于我怎样才能从一个街区提前归还一些东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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