Ruby while do-while Loop
The while
loop in Ruby is used to execute a block of code repeatedly until the given condition is true. However, sometimes we need to execute the block of code at least once, even if the given condition is false. This is where the do-while
loop comes into play.
Syntax
The syntax for the while do-while
loop in Ruby is as follows:
begin
# code to be executed
end while condition
In this loop, the code in the begin
block is executed first, and then the given condition is checked. If the condition is true
, the code in the begin
block is executed again. This process continues until the condition becomes false
.
Example
Let's see an example of using the while do-while
loop in Ruby.
i = 1
begin
puts i
i += 1
end while i <= 5
In this example, the loop prints the values of i
from 1 to 5. Even though the condition i <= 5
is false for i = 6
, the code in the begin
block is executed at least once because of the do-while
loop.
Output
The output of the above example will be:
1
2
3
4
5
Explanation
The while do-while
loop in Ruby is similar to the regular while
loop, except that the begin
block of code is always executed at least once, even if the condition is false. The loop first executes the begin
block, and then checks the condition. If the condition is true, it repeats the process. If the condition is false, it exits the loop.
Use
The while do-while
loop is useful when we want to execute a block of code at least once, even if the given condition is false. It can also be used for input validation, error checking, and other cases where we need to execute a block of code multiple times.
Important Points
- The
do-while
loop in Ruby is also known as thebegin-while
loop. - The code in the
begin
block is executed at least once, even if the condition is false- The condition is checked after thebegin
block is executed, and if it's true, the block is executed again. - The
do-while
loop is useful when we need to execute a block of code at least once, even if the given condition is false.
Summary
In this tutorial, we learned about the while do-while
loop in Ruby. We saw the syntax, example, output, explanation, use cases, important points, and summary of the loop. We can use this loop whenever we need to execute a block of code at least once, even if the given condition is false.