From: Kedar Mhaswade Date: 2011-01-07T05:06:25+09:00 Subject: Re: Class Initialization? Andrew Wagner wrote in post #972912: > On Thu, Jan 6, 2011 at 2:41 PM, Kedar Mhaswade > wrote: > >> > To answer this, grasshopper, I suggest you study this code, and figure >> > def initialize >> > x.output # I am counter object number 1 of 1 >> instance) and both are named count. >> >> > Well, there are two variables, on two different objects (the class and > its > instance), but the point is that they're *not* two different types. They > work the same way, they're just on two different objects. > > Here's a snipped that avoids the mean "class <<" stuff (with my > apologies > for my laziness): > > class Counter > @count = 0 > > def self.count > @count > end > > def self.count=(val) > @count = val > end > > def initialize > self.class.count += 1 > @count = self.class.count > end > > def output > puts "I am counter object number #{@count} of #{self.class.count}" > end > end > > x = Counter.new > x.output # I am counter object number 1 of 1 > > y = Counter.new > x.output # I am counter object number 1 of 2 > y.output # I am counter object number 2 of 2 > Andrew! Thank you. This makes it very clear. This particular arrangement makes clever use of instance variable. One is on the class instance and the other is on the each instance of that class. And in the process of explaining this, you also indirectly explained one question that was lurking in my mind -- are the attr_readers/writers/accessors available to class variables -- and as I understand it, they are -- by way of your previous class << self construct. Now I can safely ignore any discussion on @@ variables in any book ;) Thanks! -Kedar -- Posted via http://www.ruby-forum.com/.