ruby 嵌套函数
嵌套while循环 (Nested while loop)
When one while loop is living inside another while loop, it is known as nesting of while loop. It means that there are two while loops, the first one is acting as an outer loop and later one is behaving as the inner loop. Execution will take place in the manner that first the outer ‘while’ loop is triggered, then if the specified Boolean condition is matched the pointer will be passed to inner ‘while’ loop. In this too, if the Boolean condition stands to be true, the inner while loop body will be executed until specified condition does not come out to be false. Once the inner loop completes its execution, the pointer will be passed back to the outer for loop for its successful execution.
当一个while循环位于另一个while循环内部时 ,称为while循环嵌套。 这意味着有两个while循环,第一个作为外部循环,而后面一个作为内部循环。 执行将以首先触发外部“ while”循环的方式进行,然后如果指定的布尔条件匹配,则指针将传递到内部“ while”循环。 同样,如果布尔条件成立,则将执行内部while循环主体,直到指定条件不为假为止。 内部循环完成执行后,指针将被传递回外部for循环以成功执行。
In Ruby, Nesting of the while loop can be done with the help of the following syntax:
在Ruby中, while循环的嵌套可以借助以下语法来完成:
while (condition )
while (condition )
# code to be executed
end
#expressions
end
Example 1:
范例1:
We can print various patterns using nested while loops. Let us see how the following pattern can be printed.
我们可以使用嵌套的while循环打印各种模式。 让我们看看如何打印以下图案。
1
22
333
4444
55555
Code:
码:
=begin
Ruby program to print a pattern using nested while loop
=end
num=0
while (num!=6)
j=0
while(j!=num)
print num
j+=1
end
puts ""
num+=1
end
Example 2:
范例2:
=begin
Ruby program to check number of palindrome numbers present
between two limits using nested while loop
=end
puts "Enter upper limit:-"
ul=gets.chomp.to_i
puts "Enter lower limit:-"
ll=gets.chomp.to_i
while(ul!=ll)
num=ul
temp=ul
pal=0
while(num!=0)
rem=num%10
num=num/10
pal=pal*10+rem
end
if temp==pal
puts "#{temp} is palindrome"
end
ul=ul-1
end
Output
输出量
Enter upper limit:-
200
Enter lower limit:-
10
191 is palindrome
181 is palindrome
171 is palindrome
161 is palindrome
151 is palindrome
141 is palindrome
131 is palindrome
121 is palindrome
111 is palindrome
101 is palindrome
99 is palindrome
88 is palindrome
77 is palindrome
66 is palindrome
55 is palindrome
44 is palindrome
33 is palindrome
22 is palindrome
11 is palindrome
You can observe in the above program that first the outer while loop is checked through a specified condition i.e. while loop will run until upper limit does not become equal to the lower limit.
您可以在上面的程序中观察到,首先通过指定条件检查外部while循环,即while循环将运行直到上限不等于下限。
The upper limit is passed as the number for which Palindrome check will be carried out using an inner while loop. The inner while loop has all those statements which are necessary to carry out the checking. Once, the inner evaluation is done. The pointer is going back to the outer loop and the upper limit is getting decreased by 1.
上限通过使用内部while循环执行回文检查的次数来传递。 内部while循环具有执行检查所需的所有那些语句。 一次,完成内部评估。 指针返回外循环,上限减小1。
翻译自: https://www.includehelp.com/ruby/nested-while-loop-with-examples.aspx
ruby 嵌套函数