Home »
Ruby Tutorial
Ruby Nested For Loop
By IncludeHelp Last updated : November 16, 2024
Nested for loop
Nesting of for loop means one for loop is available inside another for loop. It means that there are two loops, then the first one is an outer loop and the second one is the inner loop. Execution will take place in the manner that first the outer for loop is triggered, then if the condition is matched the pointer will be passed to the inner loop. Here also if the condition is satisfied, the inner for loop body will be executed until specified condition does not comes out to be false. Once the inner loop completes its execution, the pointer will be passed back to the outer for loop for its successful execution.
Syntax
In Ruby, Nesting of for loop can be done with the help of the following syntax:
for variable_name[, variable...] in expression [do]
#expressions
for variable_name[, variable...] in expression [do]
# code to be executed
end
#expressions
end
Example 1: Demonstrate Nested for Loop
=begin
Ruby program to demonstrate nested for loop
=end
puts "Enter the upper limit:"
ul = gets.chomp.to_i
puts "Enter the lower limit:"
ll = gets.chomp.to_i
for i in ll..ul do
for j in 0..3 do
puts "Inner loop triggered"
end
puts "Outer loop triggered"
end
Output
Enter upper limit
90
Enter Lower limit
85
Inner loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Outer loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Outer loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Outer loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Outer loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Outer loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Inner loop triggered
Outer loop triggered
You can observe in the above example that first the outer for loop is invoked then the pointer has moved to inner loop and it is printing the message for times.
Once the inner for loop completes its task, the pointer goes back to the outer loop.
Example 2: Print a Pattern Using Nested for Loop
Patterns can also be printed using nested for loop. Now let us have a quick view of how the following pattern can be printed.
*
**
***
****
*****
=begin
Ruby program to print a pattern using nested for loop
=end
for i in 1..5 do
for j in 1..i do
print "*" # Print asterisk without a newline
end
puts "" # Move to the next line after inner loop completes
end