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
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 |
# File 'objspace.c', line 781
static VALUE
reachable_objects_from(VALUE self, VALUE obj)
{
if (rb_objspace_markable_object_p(obj)) {
VALUE ret = rb_ary_new();
struct rof_data data;
if (rb_typeddata_is_kind_of(obj, &iow_data_type)) {
obj = (VALUE)DATA_PTR(obj);
}
data.refs = st_init_numtable();
data.internals = rb_ary_new();
rb_objspace_reachable_objects_from(obj, reachable_object_from_i, &data);
st_foreach(data.refs, collect_values, (st_data_t)ret);
return ret;
}
else {
return Qnil;
}
}
|