Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have you ever used a "class instance variable" in any of your Ruby code?

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?

like image 507
pez_dispenser Avatar asked May 20 '09 23:05

pez_dispenser


2 Answers

Say you want to count the number of instances of a class (not including subclasses)

class A
  @count = 0
  @@count = 0
  def self.inherited(subclass)
    subclass.instance_eval { @count = 0 }
  end
  def self.num_instances
    @count
  end
  def self.num_subclass_instances
    @@count
  end
  def self.new
    @count += 1
    @@count += 1
    super
  end
end
class B < A
end
class C < B
end

A.new
B.new
A.new
B.new
B.new
C.new

A.num_instances #=> 2
A.num_subclass_instances #=> 6
B.num_instances #=> 3
B.num_subclass_instances #=> 6
C.num_instances #=> 1
C.num_subclass_instances #=> 6

You can't use the class variable, since that's shared among all classes and its subclasses. Note how the changes made to @@count by B and C are reflected in A, but @count is 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.

like image 198
rampion Avatar answered Oct 19 '22 18:10

rampion


Class variables are shared across all instances of a class, which includes all subclasses. Sometimes this variable across a hierarchy is exactly what is needed, but sometimes you might prefer a different variable for each class. Unlike class variables, class instance variables will take different values for each class object.

http://martinfowler.com/bliki/ClassInstanceVariable.html

like image 37
p01nd3xt3r Avatar answered Oct 19 '22 19:10

p01nd3xt3r