Can anyone tell me about the difference between class variables and class instance variables?
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- gem cleanup shows error: Unable to uninstall bundl
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
- ruby - simplify string multiply concatenation
First you must understand that classes are instances too -- instances of the
Class
class.Once you understand that, you can understand that a class can have instance variables associated with it just as a regular (read: non-class) object can.
Note that an instance variable on
Hello
is completely unrelated to and distinct from an instance variable on an instance ofHello
A class variable on the other hand is a kind of combination of the above two, as it accessible on
Hello
itself and its instances, as well as on subclasses ofHello
and their instances:Many people say to avoid
class variables
because of the strange behaviour above, and recommend the use ofclass instance variables
instead.A class variable (
@@
) is shared among the class and all of its descendants. A class instance variable (@
) is not shared by the class's descendants.Class variable (
@@
)Let's have a class Foo with a class variable
@@i
, and accessors for reading and writing@@i
:And a derived class:
We see that Foo and Bar have the same value for
@@i
:And changing
@@i
in one changes it in both:Class instance variable (
@
)Let's make a simple class with a class instance variable
@i
and accessors for reading and writing@i
:And a derived class:
We see that although Bar inherits the accessors for
@i
, it does not inherit@i
itself:We can set Bar's
@i
without affecting Foo's@i
: