Mar*_*ski 627 ruby continue keyword
在C和许多其他语言中,有一个continue
关键字,当在循环内部使用时,会跳转到循环的下一个迭代.continue
Ruby中有这个关键字的等价物吗?
Ian*_*ton 905
是的,它被称为next
.
for i in 0..5
if i < 2
next
end
puts "Value of local variable is #{i}"
end
Run Code Online (Sandbox Code Playgroud)
这输出如下:
Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
=> 0..5
Run Code Online (Sandbox Code Playgroud)
Nic*_*ore 106
next
另外,看一下当前迭代的redo
重做.
sbe*_*ley 82
用稍微惯用的方式写Ian Purton的答案:
(1..5).each do |x|
next if x < 2
puts x
end
Run Code Online (Sandbox Code Playgroud)
打印:
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
sep*_*p2k 41
内部for循环和iterator方法each
以及ruby中map
的next
关键字将具有跳转到循环的下一次迭代的效果(与continue
C中相同).
然而它实际上只是从当前块返回.因此,您可以将它与任何采用块的方法一起使用 - 即使它与迭代无关.
归档时间: |
|
查看次数: |
226204 次 |
最近记录: |