至關於Ruby中的「繼續」

在C和許多其餘語言中,有一個continue關鍵字,當在循環內部使用時,會跳轉到循環的下一次迭代。 Ruby中有這個continue關鍵字的等價物嗎? ruby


#1樓

用稍微慣用的方式寫Ian Purton的答案spa

(1..5).each do |x|
  next if x < 2
  puts x
end

打印: code

2
  3
  4
  5

#2樓

each for循環和迭代器方法中,而且在ruby中map next關鍵字將具備跳轉到循環的下一次迭代的效果(與C中的continue相同)。 get

然而它實際上只是從當前塊返回。 所以,您能夠將它與任何採用塊的方法一塊兒使用 - 即便它與迭代無關。 io


#3樓

我認爲這是下一個for循環


#4樓

是的, next叫它。 循環

for i in 0..5
   if i < 2
     next
   end
   puts "Value of local variable is #{i}"
end

這輸出以下: map

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

#5樓

next 迭代器

另外,請看redo 當前的迭代。 bug

相關文章
相關標籤/搜索