1

I am trying to use a class variable in ruby. But class variables change throughout the entire hierarchy, and thus are useless for this goal:

Assume I have 3 classes, each inherited, except the parent.

class A
end

class B < A
end

class C < B
end

How would I modify or create a static variable in the middle class so that class A does not have it but class C does.

B.num = 2

A.num # undefined or nil
C.num # 2

I should also specify that A.num should still be able to be used, without changing B.num or C.num, unless its inherited.

Alex V
  • 18,176
  • 5
  • 36
  • 35
  • Why is a class variable "useless"? Your sentence does not logically follow. – sawa Jan 07 '14 at 22:51
  • @sawa I don't believe my sentence does not flow. A Class Variable on class B will change the class variable on class A as well. It will change parents and children. Please review this answer: http://stackoverflow.com/questions/1251352/ruby-inherit-code-that-works-with-class-variables?answertab=votes#tab-top – Alex V Jan 07 '14 at 23:01
  • You did not seem to understand my comment correctly. I am mentioning that the fact that class variables are shared among the hierarchy does not lead to your conclusion that class variables are useless. I am asking for the basis of your claim that class variables are useless. – sawa Jan 07 '14 at 23:03
  • That answer says @@variables are not class variables... – Tony Hopkinson Jan 07 '14 at 23:07
  • Obviously class variables are not useless. They don't work as expected for my desired goal. – Alex V Jan 07 '14 at 23:08
  • That makes sense, but you wrote that they are useless. – sawa Jan 07 '14 at 23:10
  • Here is another example of class variables used as global vars. http://www.sitepoint.com/class-variables-a-ruby-gotcha/ – Alex V Jan 07 '14 at 23:14

1 Answers1

3

Edited since the OP changed the question

Use a class instance variable for A and B.

class A
  singleton_class.class_eval{attr_accessor :num}
end

class B < A
  singleton_class.class_eval{attr_accessor :num}
end

class C < B
  def self.num; superclass.num end
  def self.num= v; superclass.num = v end
end

B.num = 2
A.num # => nil
C.num # => 2
sawa
  • 165,429
  • 45
  • 277
  • 381
  • To add on to Sawa's answer: If you later decided that B should not override num, then you have to copy the definition of `self.num` from C into B. Every class that has a `num` or delegates to its super class must still have a few lines of code for `num`. – David Grayson Jan 07 '14 at 23:18