相当于“继续”。在红宝石中
在 C 和许多其他语言中,有一个 continue
关键字,当在循环内部使用时,会跳转到循环的下一次迭代。 Ruby 中是否有与此 continue
关键字等效的内容?
In C and many other languages, there is a continue
keyword that, when used inside of a loop, jumps to the next iteration of the loop. Is there any equivalent of this continue
keyword in Ruby?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
是的,它叫做
next
。输出如下:
Yes, it's called
next
.This outputs the following:
next
另外,查看
redo
,它重做当前迭代。next
also, look at
redo
which redoes the current iteration.以稍微更惯用的方式编写Ian Purton的答案:
打印:
Writing Ian Purton's answer in a slightly more idiomatic way:
Prints:
在 for 循环和迭代器方法(例如
each
和map
)中,ruby 中的next
关键字将具有跳转到循环的下一次迭代的效果(与 C 中的继续
相同)。然而它实际上所做的只是从当前块返回。因此,您可以将它与任何采用块的方法一起使用 - 即使它与迭代无关。
Inside for-loops and iterator methods like
each
andmap
thenext
keyword in ruby will have the effect of jumping to the next iteration of the loop (same ascontinue
in C).However what it actually does is just to return from the current block. So you can use it with any method that takes a block - even if it has nothing to do with iteration.
Ruby 还有另外两个循环/迭代控制关键字:
redo
和retry
。在 Ruby QuickTips 中了解有关它们以及它们之间差异的更多信息。
Ruby has two other loop/iteration control keywords:
redo
andretry
.Read more about them, and the difference between them, at Ruby QuickTips.
我认为它被称为下一个。
I think it is called next.
使用可以使用下一个条件
输出:
Use may use next conditionally
output:
使用 next,它将绕过该条件,其余代码将起作用。
下面我提供了完整的脚本和输出
:
输入号码
10
1
2
3
4
6
7
8
9
10
Use next, it will bypass that condition and rest of the code will work.
Below i have provided the Full script and out put
Output:
Enter the nmber
10
1
2
3
4
6
7
8
9
10
后期添加:您可能根本不想使用
next
,而是拒绝任何小于2
的值,然后打印其余的值。通过使用#lazy,我们可以避免在
.reject { |x| 处创建中间数组。 x < 2 }
阶段。对于如此小的样本量来说意义不大,但如果我们在(0..10_000_000)
上运行它,就会更有意义。Late addition: you may not want to use
next
at all, but rather reject any values less than2
and then print the rest.By using
#lazy
we avoid the creation of an intermediate array at the.reject { |x| x < 2 }
stage. Not very meaningful for such a small sample size, but if we ran this on(0..10_000_000)
for instance, it would be much more meaningful.