在C和许多其他语言中,有一个continue关键字,当在循环中使用时,它会跳转到循环的下一个迭代。在Ruby中是否有与continue关键字相同的关键字?
当前回答
是的,它叫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
其他回答
我想它叫next。
在for-loops和迭代器方法中,例如each和map the next关键字,在ruby中具有跳转到循环的下一次迭代的效果(与C中的continue相同)。
然而,它实际上所做的只是从当前块返回。所以你可以将它用于任何需要块的方法——即使它与迭代无关。
用一种更地道的方式来写伊恩·伯顿的回答:
(1..5).each do |x|
next if x < 2
puts x
end
打印:
2
3
4
5
Ruby还有另外两个循环/迭代控制关键字:重做和重试。 在Ruby QuickTips上阅读更多关于它们以及它们之间的区别。
是的,它叫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
推荐文章
- 是否可以在MiniTest中运行单个测试?
- 如何在Ruby中生成a和b之间的随机数?
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 如何在Ruby中创建文件
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- 如何测试参数是否存在在轨道
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- RVM不是一个函数,用' RVM use…’不会起作用
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法