ruby 2.6.1_Ruby do ... while循环示例
ruby 2.6.1
do while循环 (The do while loop)
In programming, do…while loop works in the same way as a while loop with a basic difference that the specified Boolean condition is evaluated at the end of the block execution. This result in the execution of statements at least for once and later iterations depend upon the result of the Boolean expression. A process symbol and a Boolean condition is used to make a do…while iteration.
在编程中, do … while循环的工作方式与while循环相同,基本区别是在块执行结束时评估指定的布尔条件。 这导致语句至少执行一次,以后的迭代取决于布尔表达式的结果。 使用过程符号和布尔条件进行do … while迭代 。
In this loop, at first, the block defined inside the code is executed then the given condition is checked. Due to this property, it is also known as post-test loop.
在此循环中,首先,执行代码内部定义的块,然后检查给定条件。 由于此属性,它也称为测试后循环。
A do…while loop is an example of the exit-control loop because in this the code is executed before the evaluation of the specified condition. It runs till the Boolean condition stands to be true, once it evaluates to be false the loop gets terminated at that point of time.
do … while循环是退出控制循环的一个示例,因为在这种情况下,代码是在评估指定条件之前执行的。 它一直运行到布尔条件为真为止,一旦评估为假,则该循环在该时间点终止。
In Ruby, the do…while loop is implemented with the help of the following syntax:
在Ruby中, do … while循环是通过以下语法实现的:
loop do
# code block to be executed
break if Boolean_Expression #use of break statement
end
Example 1:
范例1:
=begin
Ruby program to check whether the given
number is Armstrong or not using a do-while loop
=end
puts "Enter the number"
num=gets.chomp.to_i
temp=num
sum = 0
loop do
#implementation of the do-while loop
rem=num%10
num=num/10
sum=sum+rem*rem*rem
puts "Checking......"
if num==0
break
end
end
if(temp==sum)
puts "The #{temp} is Armstrong"
else
puts "The #{temp} is not Armstrong"
end
Output
输出量
First run:
Enter the number
135
Checking......
Checking......
Checking......
The 135 is not Armstrong
Second run:
Enter the number
1
Checking......
The 1 is Armstrong
Example 2:
范例2:
=begin
Ruby program to check wether the given number
is having five or not using do-while loop
=end
puts "Enter the number"
num=gets.chomp.to_i
temp=num
sum = 0
flag=false #flag is a Boolean variable
loop do
#implementation of the do-while loop
rem=num%10
num=num/10
if(rem==5)
flag=true #flag is made true if the presence is found
end
puts "Checking......"
if num==0
break
end
end
if(flag==true)
puts "We have found the presence of five in #{temp}"
else
puts "We have not found the presence of five in #{temp}"
end
Output
输出量
First run:
Enter the number
1234566
Checking......
Checking......
Checking......
Checking......
Checking......
Checking......
Checking......
We have found the presence of five in 1234566
Second run:
Enter the number
198762
Checking......
Checking......
Checking......
Checking......
Checking......
Checking......
We have not found the presence of five in 198762
翻译自: https://www.includehelp.com/ruby/do-while-loop-with-examples.aspx
ruby 2.6.1
还没有评论,来说两句吧...