在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
另外,看看重做当前迭代的redo。
用一种更地道的方式来写伊恩·伯顿的回答:
(1..5).each do |x|
next if x < 2
puts x
end
打印:
2
3
4
5
使用next,它将绕过该条件,其余代码将正常工作。 下面我提供了完整的脚本和输出
class TestBreak
puts " Enter the nmber"
no= gets.to_i
for i in 1..no
if(i==5)
next
else
puts i
end
end
end
obj=TestBreak.new()
输出: 输入号码 10
1 2 3 4 6 7 8 9 10
是的,它叫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
在for-loops和迭代器方法中,例如each和map the next关键字,在ruby中具有跳转到循环的下一次迭代的效果(与C中的continue相同)。
然而,它实际上所做的只是从当前块返回。所以你可以将它用于任何需要块的方法——即使它与迭代无关。
推荐文章
- RVM不是一个函数,用' RVM use…’不会起作用
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- 如何使用RSpec的should_raise与任何类型的异常?
- 如何创建退出消息
- 忽略GEM,因为没有构建它的扩展