Ruby has BEGIN {} and END {} blocks that guarantee they run before and after the main portion of code, respectively.
I have the following code:
BEGIN {
$my_args = ARGV.dup
ARGV.clear
} # clean up 'gets'
# For the truly paranoid in all of us
def self.run_away?
print "You're paranoid. Exit? (Y/n) "
ans = gets.chomp.downcase
if ["no", "n"].include?(ans)
puts "Alright, your call. Let's keep going."
else
puts "EXITING"
log("Exiting at paranoid users request.")
exit 3
end
end
END { } # do stuff here
I have a handful of error codes that I have defined in my script.
I would like to be able to read the error code and print a short description based on that code. E.g. - EXITING - 3: Exit at user request instead of writing a descriptive string every time I use an exit in my code. Is there a way to do this in the END {} block? Or something else I am missing?
Edit/Note: I'm stuck with Ruby 1.8.7 and the following doesn't work: (see below)
BEGIN { puts "BEGIN block!" }
puts "Main block!"
exit 3
END {
puts "END block!"
puts "Current Exception: \n#{$!}"
puts "Current Backtrace: \n#{$@}"
}
Output:
~: $ ./test.rb
BEGIN block!
Main block!
~: $ echo $?
3
~: $
Edit #2: I had to define my END block before I exited. Thanks to @Stefan