Ruby基础知识-循环语句 while、util、for

while:

print("the use of while");
a=1
while a <10
print a," "
a=a+1
end

until:

print("the use of until ");
a=1
until a >=10
print a," "
a=a+1
end


在循环体内,如果遇到:
break ,跳出当层循环;
next ,忽略本次循环的剩余部分,开始下一次的循环;
redo ,重新开始循环,还是从这一次开始;
retry ,重头开始这个循环体。


break:

puts "display break"
c='a'
for i in 1..4

if i == 2 and c =='a'
c = 'b'
print "\n"
break
end
print i,c," "
end
puts "\n\n"
#演示break#

next:

puts "display next"
c='a'
for i in 1..4
if i == 2 and c =='a'
c = 'b'
print "\n"
next
end
print i,c," "
end
puts "\n\n"

redo:

puts "display redo"
c='a'
for i in 1..4
if i == 2 and c =='a'
c = 'b'
print "\n"
redo
end
print i,c," "
end
puts "\n\n"

变量 c 在循环体之前赋值为 'a' ,程序执行到第 2 次,c 又赋值为 'b',遇到 redo ,重新开始循环,还是从这一次开始 ,此时,c = 'b',i = 2。


puts "演示retry"
c='a'
for i in 1..4
if i == 2 and c =='a'
c = 'b'
print "\n"
retry
end
print i,c," "
end
puts "\n\n"

1a
1b 2b 3b 4b

变量 c 在循环体之前赋值为 'a' ,程序执行到第 2 次,c 又赋值为 'b',遇到 retry ,重头开始这个循环体 ,此时,c = 'b',i = 1。


猜你喜欢

转载自blog.csdn.net/SDN_SUPERUSER/article/details/37744017