[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Class Variables for subclases...

Sonny Chee

3/27/2007 2:38:00 AM

Hey Guys,

Check out the following:

class A
@@anobject = 'green'
def fun2
@@anobject
end
end

class B < A
@@anobject = 'blue'
def fun2
@@anobject
end
end

puts B.new.fun2 # blue
puts A.new.fun2 # blue

So it looks like the subclass B is not defining its own class variable
but reusing A's class variable @@anobject. Is there a different way to
specify class variables to overcome this issue?

Sonny.

--
Posted via http://www.ruby-....

2 Answers

Joel VanderWerf

3/27/2007 3:34:00 AM

0

Sonny Chee wrote:
> Hey Guys,
>
> Check out the following:
>
> class A
> @@anobject = 'green'
> def fun2
> @@anobject
> end
> end
>
> class B < A
> @@anobject = 'blue'
> def fun2
> @@anobject
> end
> end
>
> puts B.new.fun2 # blue
> puts A.new.fun2 # blue
>
> So it looks like the subclass B is not defining its own class variable
> but reusing A's class variable @@anobject. Is there a different way to
> specify class variables to overcome this issue?
>
> Sonny.
>

You may find it more suitable to use instance variables in your class
objects, and write accessors so you can get at them from instances of
your classes.

For example:

class A
@anobject = 'green'
def self.anobject
@anobject
end
def fun2
self.class.anobject
end
end

class B < A
@anobject = 'blue'
end

puts B.new.fun2 # blue
puts A.new.fun2 # green


Google (or search the list) for 'ruby class instance variable'.

I think the 'traits' gem does this in a systematic way, though of course
it's worth playing around to understand the concept first.

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Sonny Chee

3/27/2007 3:39:00 AM

0

Thanks for the pointers Joel.

Sonny.

--
Posted via http://www.ruby-....