Ruby, like many other programming languages, supports loops. When we're working with a loop, there are times when we might need to get out of . In such cases, Ruby provides us a simple way out using its break and exit statements.
Even though both of the statements can get us out of a loop, the exit statement stops the whole program while the break statement allows us to continue the rest of the program ahead of the loop.
Both can be used according to different use cases, as required in the application. For example, when running a game, a loop is run over the program for continuous input. There will always be a specific input that lets us exit the game. If we want to exit the game instantly without any processing of feedback from the user, we will use the exit command. Whereas, if we want the user to be prompted, we can use the break command to run into an exit method and then manage the rest accordingly.
You can see how the two statements work in the example below.
break statement)x = 0while truex = x + 1puts "#{x}"breakendputs "Exited out of loop."
break statement is called to exit the loop."Exited out of loop.".break statement helps us to exit the loop and the program continues to run normally after the loop.exit statement)x = 0while truex = x + 1puts "#{x}"exitendputs "Exited out of loop."
x."Exited out of loop.".exit statement quits the program without executing any other statement.Free Resources