嵌套的for循环意味着一个for循环在另一个for循环内可用。这意味着有两个循环,然后第一个是外部循环,第二个是内部循环。执行将以首先触发外部for循环的方式进行,然后如果条件匹配,则指针将传递到内部循环。同样,如果满足条件,则内部for循环主体将一直执行到指定条件不为假为止。一旦内部循环完成其执行,该指针将被传递回外部for循环以成功执行。
在Ruby中,可以使用以下语法来完成for循环的嵌套:
for variable_name[, variable...] in expression [do] #expressions for variable_name[, variable...] in expression [do] # 要执行的代码 end #expressions end
范例1:
=begin Ruby program to demonstrate nested for loop =end puts "Enter upper limit" ul=gets.chomp.to_i puts "Enter Lower limit" ll=gets.chomp.to_i for i in ll..ul do for i in 0..3 do puts "Inner loop triggered" end puts "Outer loop triggered" end
输出结果
Enter upper limit 90 Enter Lower limit 85 Inner loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Outer loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Outer loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Outer loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Outer loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Outer loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Inner loop triggered Outer loop triggered
您可以在上面的示例中观察到,首先调用了外部for循环,然后指针移至了内部循环,并且多次打印该消息。
内部for循环完成其任务后,指针将返回到外部循环。
范例2:
也可以使用嵌套的for循环来打印图案。现在让我们快速了解如何打印以下图案。
* ** *** **** *****
码:
=begin Ruby program to print a pattern using nested for loop =end for i in 1..5 do for j in 1..i do print "*" end puts "" end