Let´s say I have a logger class that has an attribute pointing to an open file. This file should be open until this class is no longer used. Something like:
class MyLogger
attr_accessor :log_file
def initialize
@log_file = File.new('my_log_file_name.log','w')
end
def finalize(id)
@log_file.close
end
end
How can I ensure that when I will no longer use this instance, the file handle will be closed? I´ve tried this but with no effect:
l = MyLogger.new
l = nil
ObjectSpace.garbage_collect
After this, if I try to delete the file it will throw an error stating that the file is in use.
Just close tha file handle through a method call. It does not really make sense to do it any other way, especially waiting for the garbage collector. If you know hen you are done with it do your cleanup at that point.