Possible Duplicate:
Difference between class variables and class instance variables?
While reading a Ruby book, I seem to have missed the variables chapter. Now I can’t seem to understand the following things:
- What is an instance variable?
- What is a class instance variable?
- What is the difference between a
variable,@instance_varand@class_instance_var?
I tried to read some posts in different blogs, but I still do not understand. Any help would be appreciated.
It’s a variable that has an idependant value that pertains to this instance of a class. For example, a
Personclass could have@nameand@ageas instance variables. All instance ofPersonhave a name and age, but each instance will have a different value for those things.This is a little wierd, but you have to realize that the
Personclass is itself an instance ofClass. So it too can have instance variables. This is often used to configure a class. Like perhaps to add an API key to a class so that all instance can be created with that data.How it persists.
variableis local. It’s simply a reference to an object. Once no code or object has a reference to this value it is destroyed via garbage collection. It only persists if you keep using it.@instance_varpersists on an instance. So long as the instance persists, the instance variables it has will as well. So long as thePersoninstance exists, that instance will have a@name.@class_instance_varpersists on the class object (which remember is an instance ofClass). So it will exist in the class object forever, since you can never really get rid of declared classes.