Possible Duplicate:
Notification of object destruction in Ruby
Ruby: Destructors?
#initialize starts functions when a class is instantiated. Just wondering if there’s an #uninitialize function. For example:
class Something
def initialize
@browser = Watir::Browser.new :chrome #opens browser
end
def stuff(url)
@browser.goto url
end
def uninitalize
@browser.quit #close browser
end
end
s = Something.new
s.stuff("google.ca")
In this case, the browser will be opened by the initialize function. Is there a way to automatically quit it?
Ruby Finalizers Aren’t Really Destructors
While you can define finalizers for Ruby objects, they aren’t really destructors as such. In fact, they aren’t triggered until after the object is destroyed. The docs say:
Rethink Your Approach
Rather than instantiating your browser instance with #new, consider a pattern more like:
Other patterns are also possible, including setting callbacks or timers within your object. Ultimately, the point is that objects should go out of scope and be garbage collected—they can’t actually destroy themselves.