ruby and 语句
Ruby中的break语句 (break statement in Ruby)
In programming, loops are needed to be terminated properly otherwise it will result in an infinite loop. In ruby, when a certain condition is met, loops are terminated via break statement. The break statement is mostly used in while loop where the value is required to be printed till the condition comes out to be true.
在编程中,需要正确终止循环,否则将导致无限循环。 在ruby中,当满足特定条件时,循环将通过break语句终止。 break语句主要用于while循环中,在该循环中需要打印该值,直到条件变为真为止。
The basic purpose of break statement is to discontinue the loop and it is called from inside the loop.
break语句的基本目的是中断循环,并从循环内部调用它。
Syntax:
句法:
break
Now, let us understand the implementation of a break statement in a Ruby program with the help of program codes.
现在,让我们借助程序代码了解Ruby程序中break语句的实现。
Example 1:
范例1:
=begin
Ruby program to demonstrate use of Break statement.
=end
puts "Enter the integer to calculate table"
num = gets.chomp.to_i
j = 1
# Using While Loop
while true
# Printing Values
tab = j * num
puts "#{num} * #{j} = #{tab}"
j += 1
if j > 10
# Using Break Statement
break
end
end
Output
输出量
RUN 1:
Enter the integer to calculate table
12
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
12 * 9 = 108
12 * 10 = 120
RUN 2:
Enter the integer to calculate table
9
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
Code logic:
代码逻辑:
In the above code, we are trying to demonstrate the significance of the break statement. We have written a code which is calculating the table of the number which is being provided by the user. We are giving a call to break statement inside 'if' condition which is working inside the 'while' loop. The break statement is working in the way that it is breaking the loop execution or you can say that it is terminating the loop when the value of j (loop variable) exceeds 10.
在上面的代码中,我们试图证明break语句的重要性。 我们编写了一个代码,用于计算用户提供的号码表。 我们正在'if'条件内调用break语句 ,该条件在'while'循环内运行 。 break语句的工作方式是中断循环执行,或者可以说,当j (循环变量)的值超过10时,该语句终止循环。
Example 2:
范例2:
=begin
Ruby program to demonstrate use of Break statement.
=end
k = 1
# Using while
while true do
# Printing Value
puts k * (k-1)
k += 1
# Using Break Statement
break if k > 5
end
Output
输出量
0
2
6
12
20
Here, the break statement is terminating loop when it finds the value of 'k' is greater than 5.
在这里,当break语句发现'k'的值大于5时,它就是终止循环。
ruby and 语句