The ObjectSpace
module contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator.
ObjectSpace
also provides support for object finalizers, procs that will be called when a specific object is about to be destroyed by garbage collection.
include ObjectSpace
a = "A"
b = "B"
c = "C"
define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
define_finalizer(a, proc {|id| puts "Finalizer two on #{id}" })
define_finalizer(b, proc {|id| puts "Finalizer three on #{id}" })
produces:
Finalizer three on 537767360
Finalizer one on 537767510
Finalizer two on 537767510
s = "I am a string" → "I am a string"
r = ObjectSpace._id2ref(s.id) → "I am a string"
r == s → true
a = 102.7
b = 95
ObjectSpace.each_object(Numeric) {|x| p x }
print "Total count: ", ObjectSpace.each_object {} ,"\n"
produces:
102.7
2.718281828
3.141592654
Total count: 372
nil
GC
).Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.