From: James Coglan Date: 2008-07-23T01:40:11+09:00 Subject: Re: simple module for "count my instances" behaviour ------=_Part_122803_28640935.1216745146214 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline > > The error message says that the @@counter class variable is not > initialized in Countable::ClassMethods (so in the population method). > Obviously, this @@counter variable is not the same as the one that is > declared when including Countable, since User.new works as expected. > > Can someone explain me why and how to solve this? I think what you really want is an instance variable in the including class, since the counter is a property of the class. The instance variable must be created anew in every including class, whereas I think your code will try to reuse Countable's @@counter variable for all classes. This code works: module Countable def initialize self.class.instance_eval do @counter ||= 0 @counter += 1 end end module ClassMethods def population return @counter || 0 end end def self.included(base) base.extend(ClassMethods) end end class User include Countable end User.new User.new puts User.population ------=_Part_122803_28640935.1216745146214--