Method: ObjectSpace.reachable_objects_from

Defined in:
objspace.c

.reachable_objects_from(obj) ⇒ Array?

MRI specific feature

Return all reachable objects from ‘obj’.

This method returns all reachable objects from ‘obj’.

If ‘obj’ has two or more references to the same object ‘x’, then returned array only includes one ‘x’ object.

If ‘obj’ is a non-markable (non-heap management) object such as true, false, nil, symbols and Fixnums (and Flonum) then it simply returns nil.

If ‘obj’ has references to an internal object, then it returns instances of ObjectSpace::InternalObjectWrapper class. This object contains a reference to an internal object and you can check the type of internal object with ‘type’ method.

If ‘obj’ is instance of ObjectSpace::InternalObjectWrapper class, then this method returns all reachable object from an internal object, which is pointed by ‘obj’.

With this method, you can find memory leaks.

This method is only expected to work except with C Ruby.

Example:

ObjectSpace.reachable_objects_from(['a', 'b', 'c'])
#=> [Array, 'a', 'b', 'c']

ObjectSpace.reachable_objects_from(['a', 'a', 'a'])
#=> [Array, 'a', 'a', 'a'] # all 'a' strings have different object id

ObjectSpace.reachable_objects_from([v = 'a', v, v])
#=> [Array, 'a']

ObjectSpace.reachable_objects_from(1)
#=> nil # 1 is not markable (heap managed) object

Returns:

  • (Array, nil)


784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'objspace.c', line 784

static VALUE
reachable_objects_from(VALUE self, VALUE obj)
{
    if (rb_objspace_markable_object_p(obj)) {
	struct rof_data data;

	if (rb_typeddata_is_kind_of(obj, &iow_data_type)) {
	    obj = (VALUE)DATA_PTR(obj);
	}

	data.refs = rb_ident_hash_new();
	data.internals = rb_ary_new();

	rb_objspace_reachable_objects_from(obj, reachable_object_from_i, &data);

        return rb_funcall(data.refs, rb_intern("values"), 0);
    }
    else {
	return Qnil;
    }
}