Class Variables
Explain please, I can not understand.
class Foo
@a = 123
@@b = 123
end
What are the advantages of variable objects-classes and the class variables? When shou开发者_如何转开发ld I use first, and in which the second?
Instance level variables area created anew for each instance of the class. For example, a variable @id
should probably be unique for each instance of Foo
. However, there may be some values that should be the same for every instance of the type. In that case, a class variable would be more appropriate.
One important side effect of class level variables is that they are shared amongst derived classes as well. This means that changing the value in a subclass of 'Foo' will change it for 'Foo' objects as well. This may be what you want, but it can be a bit surprising to find out the hard way.
For example:
class Foo
@@some_var = 1
def bar
puts(@@some_var)
end
end
class Baz < Foo
def perhaps_unexpected
@@some_var = 10
Foo.new.bar #prints '10'
end
end
Use a class variable when you want all the instances of the class to share that variable, and use an instance variable when you want each instance to have its own non-shared variable.
精彩评论