Alex Rivera | Logout

Begin, Rescue and Ensure in Ruby?

Asked 2010-02-03T11:54:15.120
638

I was wondering if ensure was the Ruby equivalent of finally in C#? Should I have:

file = File.open("myFile.txt", "w")

begin
  file << "#{content} \n"
rescue
  # handle the error here
ensure
  file.close unless file.nil?
end

or should I do this?

#store the file
file = File.open("myFile.txt", "w")

begin
  file << "#{content} \n"
  file.close
rescue
  # handle the error here
ensure
  file.close unless file.nil?
end

Does ensure get called no matter what even if an exception isn't raised?

Edit
Report

1 Answer

5

Yes, ensure like finally guarantees that the block will be executed. This is very useful for making sure that critical resources are protected e.g. closing a file handle on error, or releasing a mutex.

answered 2010-02-03T12:09:32.563

Your Answer