Home »
Ruby Tutorial
Ruby Loops
By IncludeHelp Last updated : November 16, 2024
Ruby Loops
Loops are comprised of sequentially group instructions which are executed repeatedly until a certain condition is met. Loops provide great help in making the programmer's task easier.
Types of looping statements in Ruby
Ruby supports the following types of loops:
- The while loop
- The for loop
- The do...while loop
- The until loop
1. The while Loop
In the while loop, the condition for which the loop will run is provided at the top with while keyword. It is one of the forms of the Entry control loop and the pointer gets out when the specified condition is met.
When the number of repetitions is not fixed, it is recommended to use while loop.
Syntax
while (condition )
# code to be executed
end
Example
num=5
while num!=0
puts "Number is greater than zero"
num-=1
end
Output
Number is greater than zero
Number is greater than zero
Number is greater than zero
Number is greater than zero
Number is greater than zero
In the above code, you can observe that the number of iterations was not fixed. It was dependent upon variable which is specified in the condition.
2. The for Loop
for loop is different from while loop only in the context of syntax otherwise both of them are having the same functionality. It is one of the forms of the Entry control loop and the number of iterations must be specified before the execution of the loop. It repeats over a given range of numbers.
Syntax
for variable_name[, variable...] in expression [do]
# code to be executed
end
Example
i = "Includehelp"
for l in 1..7 do
puts i
end
Output
Includehelp
Includehelp
Includehelp
Includehelp
Includehelp
Includehelp
Includehelp
3. The do...while loop
It is the kind of Exit control loop. It is very identical to while loop but with a difference that the condition is tested after the execution of specified statements. If you want that the expressions must execute at least for once, you should go for do...while loop.
Syntax
loop do
# code block
break if Condition
end
Example
num = 0
loop do
puts "Includehelp.com"
num+=1
if num==8
break
end
end
Output
Includehelp.com
Includehelp.com
Includehelp.com
Includehelp.com
Includehelp.com
Includehelp.com
Includehelp.com
Includehelp.com
4. The until Loop
until loop is the antonym of while loop as per the functionality. While loop is terminated when the condition becomes false but the until loop is terminated when the Boolean expression evaluates to be true. It is one of the examples of Entry control loop where the condition is specified before the execution of expressions.
Syntax
until conditional [do]
# code to be executed
end
Example
num = 8
until num == 13 do
puts "Hi there! Welcome to the tutorial"
num+=1
end
Output
Hi there! Welcome to the tutorial
Hi there! Welcome to the tutorial
Hi there! Welcome to the tutorial
Hi there! Welcome to the tutorial
Hi there! Welcome to the tutorial