问题描述
如果我想做这样的事情:
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 would not work here, because I do not want to stop iteration of the remaining elements.
推荐答案
next
从该块返回.块内的 break
从产生于该块的函数返回.对于 each
来说,这意味着 break
退出循环,而 next
跳转到循环的下一个迭代(即名称).您可以返回带有下一个值
和 break值
的值.
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
.
这篇关于我怎样才能从积木中尽早归还东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!