214

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
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Chris Bunch
  • 87,773
  • 37
  • 126
  • 127

3 Answers3

371

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Chris Bunch
  • 87,773
  • 37
  • 126
  • 127
  • 7
    Wow! Nice find! Too bad they didn't just overload exit with this functionality.... – Mike Stone Sep 18 '08 at 10:59
  • 58
    Note, abort exits the program with a status of false which represents a failure. exit by default exits with a status of true representing success. Make sure you use the right one for the situation. – Alex Spurling Nov 14 '11 at 18:59
  • 1
    re. Mike Stone's comment, it sometimes looks as though Ruby was written by a team of people who had no communication with one another, doesn't it? (Still, it's so easy to program in it.) – JellicleCat Mar 19 '12 at 16:34
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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 24
    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 Mar 17 '10 at 01:22
  • sunaku - while your comment is perfectly valid, I often found that being more explicit can be useful, in particular for other people reading the code lateron. – shevy Jun 21 '17 at 18:12
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 ;-)

Mike Stone
  • 44,224
  • 30
  • 113
  • 140