Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

ObjectSpace.count_objects

(?::Hash[::Symbol, ::Integer] result_hash) -> ::Hash[::Symbol, ::Integer]
ObjectSpace.count_objects(result_hash = {}) → hash

Counts the number of objects, grouped by type.

It returns a hash that looks like:

Example
{
  TOTAL: 10000,
  FREE: 3011,
  T_OBJECT: 6,
  T_CLASS: 404,
  # ...
}

The contents of the returned hash are implementation specific and may be changed in future versions without notice.

The keys starting with :T_ are live objects of a particular type. For example, :T_ARRAY is the number of arrays.

The key :FREE is the number of object slots which are empty.

The key :TOTAL is the total number of slots (which is the sum of all of the other values).

If the optional argument result_hash is given, it is overwritten and returned. This is intended to avoid the probe effect.

Example
h = {}
ObjectSpace.count_objects(h)
puts h
# => { TOTAL: 10000, T_CLASS: 158280, T_MODULE: 20672, T_STRING: 527249 }

This method is only expected to work on C Ruby.