While Loop is one kind loop used by Ruby. Let us see it in the below example to print the numbers from 1 to 10.
num = 1; while num <= 10 do puts num; num = num + 1; end
So, we are telling Ruby to print the numbers from 1 to 10.
Firstly, we are asking Ruby to store the number 1 to a variable num.
num = 1;
Then we are using the while loop.
while num <= 10 do puts num; num = num + 1; end
The above condition says, continue to be in the loop until the value of num is less than or equal to 10 (i.e. num<=10).
And inside the loop, we will increase the value of num by 1 every time it enters the loop.
num = 1; while num <= 10 do puts num; num = num + 1; end
int num = 1;
num = num + 1; i.e. 1 is added to num.
while num <= 10 do
num = num + 1;
This is the other way of writing the while loop where the while statement is written at the end of the loop block.
This loop will execute the code block at least once, because it gets into the loop first, executes the block inside the loop. Then it checks for the conditional part i.e. while num<=10.
num = 1; begin puts num; num = num + 1; end while num<=10
In this while loop there is no conditional statement in beginning of the loop. So it gets into the code block.
begin puts num; num = num + 1; end while num<=10
Finally, after executing the block inside the loop, it comes to the conditional part of the loop.