Sridhar S
Sridhar S

Reputation: 73

Equivalent to Perl's END block in Ruby

Is there a Perl equivalent END block in Ruby? In Perl, if I specify an END block, the code in that block will get executed no matter where the program bails out. It is great functionality for closing open file handles. Does Ruby support similar functionality? I tried Ruby's "END{}" block but that doesnt seem to get called if I had an exit in the code due to an error.

Thanks!

Upvotes: 3

Views: 524

Answers (2)

Andrew Marshall
Andrew Marshall

Reputation: 97004

Use at_exit, which will run regardless of whether an exception was raised or not:

at_exit { puts 'exited!' }
raise

prints "exited" as expected.

You should only consider this if you cannot use an ensure, as at_exit causes logic to reside far away from where the actual exit occurs.

Upvotes: 3

Rich Drummond
Rich Drummond

Reputation: 3519

Yes. A block may have an 'ensure' clause. Here's an example:

begin
  # This will cause a divide by zero exception
  puts 3 / 0
rescue Exception => e
  puts "An error occurred: #{e}"
ensure
  puts "I get run anyway"
end

Running this produces:

An error occurred: divided by 0
I get run anyway

Upvotes: 1

Related Questions