Count number of existing objects in Ruby

Posted . Visible to the public.

Sometimes you want to know exactly how many objects exist within your running Ruby process. Here is how:

stats = {}
ObjectSpace.each_object  {|o| stats[o.class].nil? ? stats[o.class] = 0 : stats[o.class] += 1 }; stats

=> {String=>192038, Array=>67690, Time=>2667, Gem::Specification=>2665, Regexp=>491, Gem::Requirement=>16323, Gem::StubSpecification=>2665, ...}

Maybe you want to sort it like this:

stats.sort_by {|k,v| v }
Thomas Eisenbarth
Last edit
Thomas Eisenbarth
License
Source code in this card is licensed under the MIT License.
Posted by Thomas Eisenbarth to makandra dev (2015-10-27 15:18)