Module: ObjectSpace

Relationships & Source Files
Namespace Children
Defined in: gc.c


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.

a = "A"
b = "B"

ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" })


Finalizer two on 537763470
Finalizer one on 537763480

Class Method Summary

Class Method Details

._id2ref(object_id) ⇒ Object (mod_func)

Converts an object id to a reference to the object. May not be called on an object id passed as a parameter to a finalizer.

s = "I am a string"                    #=> "I am a string"
r = ObjectSpace._id2ref(s.object_id)   #=> "I am a string"
r == s                                 #=> true

.count_objects([result_hash]) ⇒ Hash (mod_func)

Counts objects for each type.

It returns a hash, such as:

  # ...

The contents of the returned hash are implementation specific. It may be changed in future.

If the optional argument result_hash is given, it is overwritten and returned. This is intended to avoid probe effect.

This method is only expected to work on C Ruby.

.define_finalizer(obj, aProc = proc()) (mod_func)

Adds aProc as a finalizer, to be called after obj was destroyed.

.each_object([) {|obj| ... } ⇒ Fixnum (mod_func) .each_object([) ⇒ Enumerator

Calls the block once for each living, nonimmediate object in this Ruby process. If module is specified, calls the block for only those classes or modules that match (or are a subclass of) module. Returns the number of objects found. Immediate objects (::Fixnums, ::Symbols true, false, and nil) are never returned. In the example below, each_object returns both the numbers we defined and several constants defined in the ::Math module.

If no block is given, an enumerator is returned instead.

a = 102.7
b = 95       # Won't be returned
c = 12345678987654321
count = ObjectSpace.each_object(Numeric) {|x| p x }
puts "Total count: #{count}"


Total count: 7

.garbage_collectnil (mod_func) .garbage_collect(full_mark:true, immediate_sweep:true) ⇒ nil

Alias for GC.start.

.undefine_finalizer(obj) (mod_func)

Removes all finalizers for obj.