我怎样才能提前从区块中返回一些东西?
如果我想做这样的事情:
collection.each do |i|
return nil if i == 3
..many lines of code here..
end
我怎样才能达到这样的效果?我知道我可以将块内的所有内容都包装在一个大的 if 语句中,但如果可能的话,我想避免嵌套。
Break 在这里不起作用,因为我不想停止其余元素的迭代。
If I wanted to do something like this:
collection.each do |i|
return nil if i == 3
..many lines of code here..
end
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
块内的
next
从该块返回。块内的break
从生成该块的函数返回。对于each
,这意味着break
退出循环,而next
跳转到循环的下一次迭代(因此得名)。您可以使用下一个值
和中断值
返回值。next
inside a block returns from the block.break
inside a block returns from the function that yielded to the block. Foreach
this means thatbreak
exits the loop andnext
jumps to the next iteration of the loop (thus the names). You can return values withnext value
andbreak value
.在这种情况下,您可以使用break提前终止循环:
...当然,这是假设您实际上并不希望返回值,只是跳出块。
In this instance, you can use break to terminate the loop early:
...of course, this is assuming that you're not actually looking to return a value, just break out of the block.
虽然这很古老,但有时仍然让我感到困惑。我需要这个来使用
[].select {|x| 来实现更复杂的用例}
/[].reject {|x| }
。常见用例
但我需要为每次迭代生成一个特定值并继续处理
具有更复杂的逻辑:
此外,由于它与线程相关,因此此处使用
break
将发出您传入的单个值,如果条件命中:Although this is ancient, this still confuses me sometimes. I needed this for a more complicated use case with
[].select {|x| }
/[].reject {|x| }
.Common Use case
But I needed to yield a specific value for each iteration and continue processing
With more complicated logic:
Also, since it's relevant to the thread, using
break
here will emit the single value you pass in if the conditional hits: