The for loop is a useful statement when you need to loop over a specific set of values, for example, a range.
The for loop consists of an empty variable and a range. At each iteration of the loop, the empty variable will be assigned the corresponding element of the range.
for i in (1..10)
This will output the numbers 1 to 10.
During the first loop the variable i will be assigned the first value of the range, 1.
On the second loop, it will be assigned to the value 2, and so on, until the end of the range.
The break statement can be used to stop a loop.
for i in 1..5
break if i > 3
Similarly, the next statement can be used to skip one iteration of the loop and continue with the next one.
for i in 0..10
next if i %2 == 0
This will output only the odd numbers from 0 to 10 because the even numbers will skip the loop iteration.
Another looping statement in Ruby is the loop do statement.
It allows code to execute until a break condition is achieved.
x = 0
x += 1
break if x > 10
This will print the numbers 0 to 10. When x > 10 evaluates to true, the loop will stop.
CLICK ON THE BUTTON BELOW TO GO TO THE RUBY MAIN COURSE PAGE.
© License: All Rights Reserved
CONTACT HOLLA TECH – LEARN SUPPORT