Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
ObjectSpace.reachable_objects_from
static VALUE
reachable_objects_from(VALUE self, VALUE obj)
{
if (!RB_SPECIAL_CONST_P(obj)) {
struct rof_data data;
if (rb_typeddata_is_kind_of(obj, &iow_data_type)) {
obj = (VALUE)DATA_PTR(obj);
}
data.refs = rb_obj_hide(rb_ident_hash_new());
data.values = rb_ary_new();
rb_objspace_reachable_objects_from(obj, reachable_object_from_i, &data);
return data.values;
}
else {
return Qnil;
}
}
Returns all reachable objects from obj as an array:
ObjectSpace.reachable_objects_from(['a', 'b', 'c']) #=> [Array, 'a', 'b', 'c']
The returned array is deduplicated, meaning that if obj refers to another object more than once, it will only be added to the array once:
ObjectSpace.reachable_objects_from([v = 'a', v, v]) #=> [Array, 'a']
Returns nil if obj is not a markable object (i.e. non-heap managed) object. Non-markable objects include true, false, nil, certain symbols, small integers, and floats:
ObjectSpace.reachable_objects_from(1) #=> nil
All references to internal objects in the returned array are wrapped using ObjectSpace::InternalObjectWrapper objects. This object contains a reference to the internal object and the type of the object can be accessed using the ObjectSpace::InternalObjectWrapper#type method.
If obj is instance of ObjectSpace::InternalObjectWrapper, then this method returns all reachable object from the internal object.
This method is useful for debugging purposes, such as finding memory leaks.
This method is only expected to work with C Ruby.