How to create an exit message

Ruby

Ruby Problem Overview


Is there a one line function call that quits the program and displays a message? I know in Perl it's as simple as:

die("Message goes here")

I'm tired of typing this:

puts "Message goes here"
exit

Ruby Solutions


Solution 1 - Ruby

The abort function does this. For example:

abort("Message goes here")

Note: the abort message will be written to STDERR as opposed to puts which will write to STDOUT.

Solution 2 - Ruby

If you want to denote an actual error in your code, you could raise a RuntimeError exception:

raise RuntimeError, 'Message goes here'

This will print a stacktrace, the type of the exception being raised and the message that you provided. Depending on your users, a stacktrace might be too scary, and the actual message might get lost in the noise. On the other hand, if you die because of an actual error, a stacktrace will give you additional information for debugging.

Solution 3 - Ruby

I got here searching for a way to execute some code whenever the program ends.
[Found this][1]:

Kernel.at_exit { puts "sayonara" }
# do whatever
# [...]
# call #exit or #abort or just let the program end
# calling #exit! will skip the call

Called multiple times will register multiple handlers.

[1]: https://ruby-doc.org/core-2.4.1/Kernel.html#method-i-at_exit "Kernel.at_exit"

Solution 4 - Ruby

I've never heard of such a function, but it would be trivial enough to implement...

def die(msg)
  puts msg
  exit
end

Then, if this is defined in some .rb file that you include in all your scripts, you are golden.... just because it's not built in doesn't mean you can't do it yourself ;-)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris BunchView Question on Stackoverflow
Solution 1 - RubyChris BunchView Answer on Stackoverflow
Solution 2 - RubyJörg W MittagView Answer on Stackoverflow
Solution 3 - RubyGiuseView Answer on Stackoverflow
Solution 4 - RubyMike StoneView Answer on Stackoverflow