Yes it is quite simple actually once you understand it ;-). The difference between instance variables and class variables is in the scoping rules (where you can access the variable). If you set an instance variable of a particular object you can only access it from inside the object:
Code:
class Foo
def set_the_variable(value)
@the_variable = value
end
def print_the_variable
print @the_variable
end
end
Every instance of Foo has a distinct version of @the_variable:
Code:
foo1 = Foo.new
foo1.set_the_variable("foo1's variable")
foo2 = Foo.new
foo2.set_the_variable("foo2's variable")
foo1.print_the_variable # "foo1's variable"
foo2.print_the_variable # "foo2's variable"
This is what I called "instance instance variables".
A class variable is different: there is only one variable for all objects:
Code:
class Foo
def set_the_variable(value)
@@the_variable = value
end
def print_the_variable
print @@the_variable
end
end
foo1 = Foo.new
foo1.set_the_variable("foo1's variable")
foo2 = Foo.new
foo2.set_the_variable("foo2's variable") # this one overwrites foo1's variable too
foo1.print_the_variable # "foo2's variable" !!!
foo2.print_the_variable # "foo2's variable"
You can additionally access class variables in class methods:
Code:
class Foo
# ... same as before ...
def self.print_the_variable_from_the_class
print @@the_variable
end
end
foo1 = Foo.new
foo1.set_the_variable("Hi!")
Foo.print_the_variable_from_the_class # "Hi!"
You can access class variables in the class and in the instances. You can access instance variables only in the instance.
Because classes are objects they can have instance variables too. You cannot access these variables in the instances of the class (foo1 and foo2) -- only from the class itself.
Code:
class Bar
@the_variable = "Hi!"
def print_the_variable # note: this is an instance method
print @the_variable # this won't work because this instance variable doesn't exist: it belongs to the class
end
def self.print_the_variable # note: this is a class method
print @the_variable # this will work
end
end
This is what I called "class instance variables": instance variables of a Class object (Bar in this case).
Bookmarks