In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop.
3 6 9 12 15 18
In examples, break statement used with if statement. By using break statement the execution will be stopped. in above example, when i*3 will be greater than equal to 21 than execution will be stopped.
0 1 2 3
The above code restricts the number of loop iterations to 3.
next Statement :
To skip the rest of the current iteration we use next statement. When next statement is executed no other iteration will be performed. next statement is similar as continue statement in any other language.
Value of x is : 3 Value of x is : 4 Value of x is : 5 Value of x is : 6
In above example, where value is not printed till the condition is true and go to next iteration. when condition is false than value of x will be printed.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.