Understanding Ruby's do while Loop
Q: Explain do while loop in Ruby.
- Ruby
- Mid level question
Explore all the latest Ruby interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Ruby interview for FREE!
Ruby doesn't have a `do-while` loop construct, but it has an equivalent control structure called `begin..while`, which has a similar behavior. The `begin..while` loop will execute the code block at least once, and then continue executing the code block repeatedly while the specified condition is true.
The syntax for a `begin..while` loop in Ruby is as follows:
begin # code to be executed at least once end while condition
In this code, `condition` is the expression that will be evaluated at the end of each iteration of the loop, and the block of code inside the `begin`..`end` block will be executed at least once, regardless of the value of the condition.
Here's an example of how to use a `begin..while` loop in Ruby to print the numbers from 1 to 10:
i = 1 begin puts i i += 1 end while i <= 10
In this code, we initialize a variable `i` to 1, and then use a `begin..while` loop to print the value of `i` and increment it by 1 on each iteration. The loop will continue until `i` is greater than 10, at which point the condition `i <= 10` will become false and the loop will terminate.
When you run this code, it will output the following:
1 2 3 4 5 6 7 8 9 10
Note that the code block inside the `begin`..`end` block is executed at least once, regardless of the value of the condition. If the condition is initially false, the loop will still execute once before terminating.


