ruby的循环有以下几种:
times方法 for while until(与while相反)
each(与for极度相似,在ruby内部,for语句是用each实现的) loop(无限循环,与break搭档)
下 表是循环控制命令
redo | 在相同条件下重复刚才的处理 |
break | 终止全部程序,跳出循环 |
next | 跳到下一次循环 |
举例如下:break 会终止全体程序
p "break的例子"
i = 0
["a", "b", "c", "d", "e"].each do |name|
i += 1
if i ==3
break
end
p [i,name]
end #=》
"break的例子"
[1, "a"]
[2, "b"]
next使用后,程序会忽略后面的部分,开始进行下一次循环
p "next的例子"
i = 0
["a", "b", "c", "d", "e"].each do |name|
i += 1
if i ==3
next
end
p [i,name]
end #=>
"next的例子"
[1, "a"]
[2, "b"]
[4, "d"]
[5, "e"]
p "redo的例子"
i = 0
["a", "b", "c", "d", "e"].each do |name|
i += 1
if i ==3
redo
end
p [i,name]
end
"redo的例子"
[1, "a"]
[2, "b"]
[4, "c"]
[5, "d"]
[6, "e"]