今天整理一下ruby中的循环用法:
备注:“do~end”部分也可以写做{~}
1、break:直接跳出整个循环
1 i= 0 2 ["perl","python","ruby","scheme"].each{|lang| 3 i += 1 4 if i ==3 5 break 6 end 7 p [i,lang] 8 }
#=》
[1, "perl"]
[2, "python"]
2、next:会跳过这一次的循环,直接开始下一次的循环动作
1 i= 0 2 ["perl","python","ruby","scheme"].each{|lang| 3 i += 1 4 if i ==3 5 next 6 end 7 p [i,lang] 8 }
#=》
[1, "perl"]
[2, "python"]
[4, "scheme"]
3、redo:与next很相似,区别在于重复执行现在这一次循环
1 i= 0
2 ["perl","python","ruby","scheme"].each{|lang|
3 i += 1
4 if i ==3
5 redo
6 end
7 p [i,lang]
8 }
#=》
[1, "perl"]
[2, "python"]
[4, "ruby"]
[5, "scheme"]
输出这个结果是因为当i = 3 时,执行到第5行redo,这时知会跳到循环的前方,也就是第三行处继续执行,而lang的值并没有从“ruby”进入到下一个“scheme”