我怎样才能从一个街区提前归还一些东西? [英] How can I return something early from a block?
问题描述
如果我想做这样的事情:
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 value
和 break 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屋!