Search code examples
rubydestructorrubypython

ruby equivalent of destructor


I'm using RubyPython to import a Python module. I am doing RubyPython.start in the constructor (initialize), and I suppose I should symmetrically do RubyPython.stop in the destructor, but unfortunately it seems that there is no destructor in Ruby:

class QDSHiveHelper
    def initialize
        RubyPython.start
        qds = RubyPython.import('blah')
        ...
    end
    def do_something
        qds.some_function
        ...
    end 
    def finalize
        RubyPython.stop
    end
end

Could someone please explain how to accomplish this? ObjectSpace.define_finalize seems to be discouraged and has some gotchas (can't use closure etc). I could also just leave RubyPython dangling and not call stop on it, but I don't know what could be the consequences. What's the best way out?


Solution

  • There is a hook called ObjectSpace.define_finalizer that is called when an object is destroyed.