Ruby While Loop Explained for Beginners
Q: Explain 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!
In Ruby, a `while` loop is a control structure that repeatedly executes a block of code while a certain condition is true. The syntax for a `while` loop in Ruby is as follows:
while condition do # code to be executed while the condition is true end
In this code, `condition` is any expression that returns a boolean value (`true` or `false`). The block of code inside the loop will be executed repeatedly as long as the condition is true.
Here's an example of how to use a `while` loop in Ruby to print the numbers from 1 to 10:
i = 1 while i <= 10 do puts i i += 1 end
In this code, we initialize a variable `i` to 1, and then use a `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 in this example, the condition `i <= 10` is true for the values of `i` from 1 to 10, so the loop executes 10 times. However, if the condition is initially false, the loop will not execute at all. It's important to ensure that the condition eventually becomes false to avoid infinite loops.


