How do you stop a Ruby program early?
Normally a program will run until it’s done processing all the instructions.
Or until it raises an exception that doesn’t get handled.
But if you’re writing a Ruby program that doesn’t need to be running all the time, you may want to stop your program early for one reason or another.
You can do this with the
How does this exit method work?
Let’s talk about that!
Different Ways to Stop a Program
When you call
exit your program won’t stop immediately.
This is what happens:
Ruby raises a
SystemExit exception which gives other parts of your program a chance to clean up.
You can run this code to see a demonstration:
begin exit rescue SystemExit p 123 end
123 before exiting.
If you want your program to skip this clean-up process, you can use
Here’s an example:
begin exit! rescue SystemExit p 123 end
Notice how this won’t print
123 before the program ends.
You can also use another method.
With this method you can provide an error message.
abort "No Bacon Left"
Which is the same as:
warn "No Bacon Left!" exit 1
warn method prints an error message to standard error.
But what is this
1 argument for
That’s the next topic of discussion!
Understanding Status Codes
When a program ends, not just a Ruby program but ANY program, it leaves a status code behind.
Here’s what you need to know:
- A status code of
0means the program ended normally
- Other status codes (not
0) are used to signal an error condition
- The effect of returning a non-zero status code depends on your current environment
This is helpful because the operating system, or regular programs, can use this status code for monitoring, logging & even automatically restarting a failed program.
In Linux you can use
echo $? to find out the exit status code of the last program.
Let’s go back to Ruby:
When you call
exit the status code is
0 by default.
You can pass another status code as an argument.
That’s why when you call
abort the status code is set to
abort method is used to signal an error.
Stopping A Loop
If you don’t want to stop a whole program but just a loop, then you have to use something different.
You can use the
while 1 == 1 break end
Exiting A Method
Ruby methods end naturally on their last line of code.
If you would like to exit earlier…
def apples return "I had my two apples today" "bacon" end
This code never gets to
"bacon" because of the early
Bonus: Stopping An Infinite Loop
Sometimes you forget to increase a counter & produce an infinite loop.
To make your program stop you can press a key combination:
You have learned about the
exit method in Ruby, the
abort method, exit status codes, and how to break out of a loop.
Don’t forget to share this article so more people can enjoy it.
Thanks for reading! 🙂