Class Variables for subclases...

S

Sonny Chee

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.
 
S

Sonny Chee

Yukihiro said:
You can use constants-as-class-shared technique.

Thanks, Matz. For my edification, is there a reason why class variables
behave in this way when subclassed? Is this a feature of the language
or the Ruby Interpretter?

Sonny.
 
J

Joel VanderWerf

Sonny said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top