Andrew Wagner wrote in post #972567:
>
>> available from the class, without having to create any instances of it.
>>
>> --
>> Posted via http://www.ruby-forum.com/\.
>>
>>
> To answer this, grasshopper, I suggest you study this code, and figure
> out
> how it works. Hint: there are more than one @count variables.
>
> class Counter
> @count = 0
>
> class << self
> attr_accessor :count
> 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
My n00b parser is stuck at class << self for I have to yet learn that
construct, I guess.
But I will spend more time understanding this example. My first attempt
tells me that there are two types of variables (one: class, other
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
I am still influenced by the "initially straightforward" example given
···
On Thu, Jan 6, 2011 at 2:41 PM, Kedar Mhaswade <kedar.mhaswade@gmail.com>wrote:
> On Wed, Jan 5, 2011 at 12:18 PM, Kedar Mhaswade > > <kedar.mhaswade@gmail.com>wrote:
in the Pickaxe book that counts the number of Song objects created thus
far (i.e. incrementing @@count by 1 in the initialize method).
Thank you.
--
Posted via http://www.ruby-forum.com/\.