I can understand why you would need a class variable to keep track of things like the total number of objects that have been instantiated in that class.
And I can understand why you would need an instance variable to store attributes of a particular object in that class.
But class instance variables I just can’t seem to justify.
As I understand it, they’re just like class variables except that they are not visible to subclasses the way class variables are.
It seems that the uses for this would be quite limited. Or am I wrong? Has anyone found a good use for class instance variables in their code? Or could you give an example of a situation where this type of nuance would be valuable?
Say you want to count the number of instances of a class (not including subclasses)
You can’t use the class variable, since that’s shared among all
classes and its subclasses. Note how the changes made to
@@countby
BandCare reflected inA, but@countis not shared.In general, though, it can be very useful for storing any class-specific settings.
_why uses it in Dwemthy’s Array to specify initial values for instance attributes, and it comes up a lot whenever doing ruby metaprogramming.