tags:

views:

3464

answers:

4
+12  Q: 

Ruby - Exit Message

Since I got a quick response on the last Ruby question I asked, I have another one that's been bothering me. Is there a one line function call that quits the program and displays a message? I know in Perl its as simple as this:

die("Message goes here")

Essentially I'm just tired of typing this:

puts "Message goes here"
exit
+1  A: 

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

Mike Stone
Turns out the 'abort' function does it (see my answer below)
Chris Bunch
+1  A: 

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.

Jörg W Mittag
You don't need to mention RuntimeError to raise one (it's the default kind of exception raised) so the following code will suffice: raise 'Message goes here'
sunaku
A: 

Your two examples (Perl and Ruby) arent really the same thing. In Perl, die throws an exception (which can be handled). If the exception isn't handled, then the program exits with that message. The exit function causes the program to terminate, and probably cannot be handled as an exception. The "best" way to do the Perl equivalent in Ruby is probably to throw some kind of exception.

1800 INFORMATION
Ruby's exit does raise an exception: http://www.ruby-doc.org/core/classes/Kernel.html#M005956
quackingduck
Kernel.exit! doesn't raise an exception however.
Max Howell
+24  A: 

The 'abort' function does this. For example:

abort("Message goes here")
Chris Bunch
Wow! Nice find! Too bad they didn't just overload exit with this functionality....
Mike Stone