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

本文详细解析了编程中while、until循环及break、next、redo、retry流程控制关键字的功能与用法,通过具体示例展示了它们在循环体内的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值