-
-
Save herrphon/464434cf5f81dffccd7a3bbf506198a5 to your computer and use it in GitHub Desktop.
Ruby 'Destructor' example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo | |
attr_reader :bar | |
def initialize | |
@bar = 123 | |
ObjectSpace.define_finalizer( self, self.class.finalize(bar) ) | |
end | |
def self.finalize(bar) | |
proc { puts "DESTROY OBJECT #{bar}" } | |
end | |
end | |
f=Foo.new | |
puts "Foo.bar is #{f.bar} now" | |
f=nil | |
# Force ruby to start the Garbage Collector | |
# In a real program you don't have to do this | |
# ruby will run the GC automatically. | |
GC.start | |
sleep 1 # make sure you will see the message | |
# before ruby quits | |
puts "done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment