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.

7
  • Why is a class variable "useless"? Your sentence does not logically follow. Commented Jan 7, 2014 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: stackoverflow.com/questions/1251352/… Commented Jan 7, 2014 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. Commented Jan 7, 2014 at 23:03
  • That answer says @@variables are not class variables... Commented Jan 7, 2014 at 23:07
  • Obviously class variables are not useless. They don't work as expected for my desired goal. Commented Jan 7, 2014 at 23:08

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.