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.
Syntax :
Break
Example :
# Ruby program to use break statement #!/usr/bin/ruby -w i = 1 # Using While Loop while true # Printing Values puts i * 3 i += 1 if i * 3 >= 21 # Using Break Statement break end end |
Output:
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.
Example :
# Ruby program to use break statement #!/usr/bin/ruby -w x = 0 # Using while while true do # Printing Value puts x x += 1 # Using Break Statement break if x > 3end |
Output:
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.
Syntax:
next
Example :
# Ruby program of using next statement #!/usr/bin/ruby -w for x in 0..6 # Used condition if x+1 < 4 then # Using next statement next end # Printing values puts "Value of x is : #{x}" end |
Output :
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.
Recommended Posts:
- Ruby | unless Statement and unless Modifier
- Ruby redo and retry Statement
- Ruby | Case Statement
- Ruby Integer next function with example
- Ruby | Symbol next function
- Similarities and Differences between Ruby and C language
- Similarities and Differences between Ruby and C++
- Ruby | Exception Class and its Methods
- Ruby | Dir Class and its methods
- Ruby Date and Time
- Ruby Search and Replace
- BEGIN and END Blocks In Ruby
- Catch and Throw Exception In Ruby
- Ruby getters and setters Method
- Ruby | Class Method and Variables
- Difference Between Laravel and Ruby on Rails
- How to Install Ruby on Rails on Windows and Linux?
- True, False, and Nil In Ruby
- And Keyword in Ruby
- Difference Between Golang and Ruby
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

