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:
variable
, @instance_var
and @class_instance_var
?I tried to read some posts in different blogs, but I still do not understand. Any help would be appreciated.
What is an instance variable?
It's a variable that has an idependant value that pertains to this instance of a class. For example, a Person
class could have @name
and @age
as instance variables. All instance of Person
have a name and age, but each instance will have a different value for those things.
What is a class instance variable?
This is a little wierd, but you have to realize that the Person
class is itself an instance of Class
. 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.
class PersonFetcher
# class method can set class instance variables
def self.set_api_key(key)
@api_key = key
end
# instance method sets instance variables
def set_name(name)
@name = name
end
end
What is the difference between a variable, @instance_var and @class_instance_var?
How it persists.
variable
is 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_var
persists on an instance. So long as the instance persists, the instance variables it has will as well. So long as the Person
instance exists, that instance will have a @name
.
@class_instance_var
persists on the class object (which remember is an instance of Class
). So it will exist in the class object forever, since you can never really get rid of declared classes.