Equivalent of “continue” in Ruby

2019-01-16 00:08发布

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?

6条回答
等我变得足够好
2楼-- · 2019-01-16 00:46

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 
查看更多
看我几分像从前
3楼-- · 2019-01-16 00:48

Ruby has two other loop/iteration control keywords: redo and retry. Read more about them, and the difference between them, at Ruby QuickTips.

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-16 00:57

I think it is called next.

查看更多
Melony?
5楼-- · 2019-01-16 00:59

next

also, look at redo which redoes the current iteration.

查看更多
仙女界的扛把子
6楼-- · 2019-01-16 00:59

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
查看更多
唯我独甜
7楼-- · 2019-01-16 01:10

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.

查看更多
登录 后发表回答