Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
ObjectSpace.each_object
static VALUE
os_each_obj(int argc, VALUE *argv, VALUE os)
{
VALUE of;
of = (!rb_check_arity(argc, 0, 1) ? 0 : argv[0]);
RETURN_ENUMERATOR(os, 1, &of);
return os_obj_of(of);
}
Calls the block once for each living, non-immediate object in this Ruby process, and returns the number of objects found.
If module is given, calls the block only for objects that are an instance of module or one of its subclasses.
Immediate objects (such as small integers, static symbols, true, false, and nil) are never yielded.
With no block given, returns a new Enumerator.
Job = Class.new jobs = [Job.new, Job.new] count = ObjectSpace.each_object(Job) {|x| p x } puts "Total count: #{count}"
produces:
#<Job:0x000000011d6cbbf0> #<Job:0x000000011d6cbc68> Total count: 2
Because every live object is visited, this method is mainly useful for debugging, profiling, and introspecting a running process.
In multi-Ractor mode this method yields every object of the current Ractor, plus the objects of the other Ractors that have been made Ractor-shareable. Another Ractor’s unshareable objects are never yielded: they belong to that Ractor and the current one must not touch them.
c = {} # not shareable, belongs to the main Ractor r = Ractor.new { d = {}; receive } # d belongs to r ObjectSpace.each_object {|x| x } # yields c, but not d