在C语言和许多其他语言中,有一个 continue 关键字,当在循环内部使用时,会跳转到循环的下一次迭代 . Ruby中有这个 continue 关键字的等价物吗?
continue
是的,它被称为 next .
next
for i in 0..5 if i < 2 next end puts "Value of local variable is #{i}" end
这输出如下:
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
另外,请查看 redo ,它会重做当前的迭代 .
redo
以稍微惯用的方式编写Ian Purton's answer:
(1..5).each do |x| next if x < 2 puts x end
打印:
2 3 4 5
在for循环和迭代器方法中,如 each 和 map ,ruby中的 next 关键字将具有跳转到循环的下一次迭代的效果(与C中的 continue 相同) .
each
map
然而它实际上只是从当前块返回 . 因此,您可以将它与任何采用块的方法一起使用 - 即使它与迭代无关 .
Ruby有两个其他循环/迭代控制关键字: redo 和 retry . Read more about them, and the difference between them, at Ruby QuickTips .
retry
我认为它被称为next .
6 回答
是的,它被称为
next
.这输出如下:
next
另外,请查看
redo
,它会重做当前的迭代 .以稍微惯用的方式编写Ian Purton's answer:
打印:
在for循环和迭代器方法中,如
each
和map
,ruby中的next
关键字将具有跳转到循环的下一次迭代的效果(与C中的continue
相同) .然而它实际上只是从当前块返回 . 因此,您可以将它与任何采用块的方法一起使用 - 即使它与迭代无关 .
Ruby有两个其他循环/迭代控制关键字:
redo
和retry
. Read more about them, and the difference between them, at Ruby QuickTips .我认为它被称为next .