212

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
4

4 回答 4

367

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.

于 2008-09-17T18:50:05.210 回答
24

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.

于 2008-08-27T05:25:26.473 回答
2

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

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.

于 2017-04-19T08:51:30.933 回答
1

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 ;-)

于 2008-08-27T04:54:19.217 回答