What is the difference between break and exit in Ruby?

Introduction

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.

break vs. exit

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.

Code example (break statement)

x = 0
while true
x = x + 1
puts "#{x}"
break
end
puts "Exited out of loop."

Code explanation

  • Lines 1–6: A simple loop is executed to print the value of x.
  • Line 5: A break statement is called to exit the loop.
  • Line 7: Once out of the loop, the system prints the given statement "Exited out of loop.".
  • We can see that once the loop is run, the break statement helps us to exit the loop and the program continues to run normally after the loop.

Code example (exit statement)

x = 0
while true
x = x + 1
puts "#{x}"
exit
end
puts "Exited out of loop."

Code explanation

  • Lines 1–6: A simple loop is executed to print the value of x.
  • Line 5: An exit statement is called to exit the program.
  • Line 7: Once out of the loop, the system prints the given statement "Exited out of loop.".
  • We can see that once the loop is run, the exit statement quits the program without executing any other statement.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved