Skip to content
class method

ObjectSpace.each_object

(?::Module module) -> ::Enumerator[untyped, ::Integer]
(?::Module module) { (untyped obj) -> void } -> ::Integer
ObjectSpace.each_object([module]) {|obj| ... } → integer
ObjectSpace.each_object([module]) → an_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 (such as Fixnums, static Symbols true, false and nil) are never returned.

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

Example
Job = Class.new
jobs = [Job.new, Job.new]
count = ObjectSpace.each_object(Job) {|x| p x }
puts "Total count: #{count}"

produces:

Example
#<Job:0x000000011d6cbbf0>
#<Job:0x000000011d6cbc68>
 Total count: 2

Due to a current Ractor implementation issue, this method does not yield Ractor-unshareable objects when the process is in multi-Ractor mode. Multi-ractor mode is enabled when Ractor.new has been called for the first time. See bugs.ruby-lang.org/issues/19387 for more information.

Example
a = 12345678987654321 # shareable
b = [].freeze # shareable
c = {} # not shareable
ObjectSpace.each_object {|x| x } # yields a, b, and c
Ractor.new {} # enter multi-Ractor mode
ObjectSpace.each_object {|x| x } # does not yield c