From: Austin Ziegler Date: 2005-08-02T22:24:33+09:00 Subject: Re: Module that keeps track of instance count? On 8/2/05, francisrammeloo@hotmail.com wrote: > 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: > module InstanceCounter > def initialize(*args) > super > @count = 0 > end > > def increase_count() > @count += 1 > return @count - 1 > end > end I think you want, instead: module InstanceCounter def increase_count @@count ||= 0 @@count += 1 (@@count - 1) end end Note that this isn't thread-safe. It also won't help in cases where you subclass your class that includes InstanceCounter. What you'd probably want is something that deals with a class-instance variable rather than a class variable, and that would be able to be dealt with using #append_features (I think). Additionally, under the current scheme, #increase_count is a public method that anyone can call on an instance. There are examples of how to get create this count safely somewhere, I just can't recall where offhand. ;) The main trick you're after, though, is @@count ||= 0. -austin -- Austin Ziegler * halostatue@gmail.com * Alternate: austin@halostatue.ca