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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Yes, it's called next
.
for i in 0..5
if i < 2
next
end
puts "Value of local variable is #{i}"
end
This outputs the following:
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
回答2:
next
also, look at redo
which redoes the current iteration.
回答3:
Writing Ian Purton's answer in a slightly more idiomatic way:
(1..5).each do |x|
next if x < 2
puts x
end
Prints:
2
3
4
5
回答4:
Inside for-loops and iterator methods like each
and map
the next
keyword in ruby will have the effect of jumping to the next iteration of the loop (same as continue
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.
回答5:
Ruby has two other loop/iteration control keywords: redo
and retry
.
Read more about them, and the difference between them, at Ruby QuickTips.
回答6:
I think it is called next.