Alex V
Alex V

Reputation: 18306

Ruby Static Inheritance

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.

Upvotes: 1

Views: 678

Answers (1)

sawa
sawa

Reputation: 168131

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

Upvotes: 3

Related Questions