diff --git a/README.md b/README.md index 3a7b22d..394cb4d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1194 TILs and counting..._ +_1195 TILs and counting..._ --- @@ -948,6 +948,7 @@ _1194 TILs and counting..._ - [Enumerate A Pairing Of Every Two Sequential Items](ruby/enumerate-a-pairing-of-every-two-sequential-items.md) - [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md) - [Exclude Values From An Array](ruby/exclude-values-from-an-array.md) +- [Exit A Process With An Error Message](ruby/exit-a-process-with-an-error-message.md) - [Expect A Method To Be Called And Actually Call It](ruby/expect-a-method-to-be-called-and-actually-call-it.md) - [Extract A Column Of Data From A CSV File](ruby/extract-a-column-of-data-from-a-csv-file.md) - [FactoryGirl Sequences](ruby/factory-girl-sequences.md) diff --git a/ruby/exit-a-process-with-an-error-message.md b/ruby/exit-a-process-with-an-error-message.md new file mode 100644 index 0000000..5e34a41 --- /dev/null +++ b/ruby/exit-a-process-with-an-error-message.md @@ -0,0 +1,34 @@ +# Exit A Process With An Error Message + +If you want to exit a Ruby process with an unsuccessful error code like `1`, +you can use +[`Kernel.exit`](https://ruby-doc.org/core-3.1.2/Kernel.html#method-i-exit). + +```ruby +if arg_is_missing? + exit 1 +end +``` + +The non-zero status code means this will work great in a scripting scenario, +like `ruby script.rb && echo 'success'`. If the script has to exit early, it +won't print 'success'. + +That's fine, but it doesn't give the program a chance to tell us _why_ the +program exited early. + +`Kernel` has another method +[`abort`](https://ruby-doc.org/core-3.1.2/Kernel.html#method-i-abort) that does +the same thing as `exit 1` while also printing a message to `STDERR`. + +```ruby +if arg_is_missing? + abort 'The missing argument must be supplied' +end +``` + +This is handy if you want to communicate more than just the error code. The +program still exits early with an error code of `1`. And it prints that message +to `STDERR`. + +[source](https://stackoverflow.com/a/23340693/535590)