From: Dave Burt Date: 2005-08-03T10:21:05+09:00 Subject: Re: Module that keeps track of instance count? wrote... > Hi, > > I need some of my classes to keep track of their number of instances. > To avoid duplication I thought it was a good idea to put this > functionality in a separate module: > Here's a different way to do it: module InstanceCounter def instance_count(include_subclasses = true) count = 0 GC.start # <- this line is optional ObjectSpace.each_object do |obj| count += 1 if obj.class == self || include_subclasses && obj.kind_of?(self) end count end end class Foo extend InstanceCounter end class Bar < Foo end Foo.instance_count #=> 0 Bar.instance_count #=> 0 a = [Foo.new, Bar.new, Bar.new] Foo.instance_count #=> 3 Foo.instance_count(false) #=> 1 Bar.instance_count #=> 2 Cheers, Dave