Variables in Ruby
Ruby is a OO language, but the categories of variable it supports are a bit different from Java or C#.
In Java and C#, there are two kinds of variables, instance variables (tied to class instances, aka objects) and static variables (tied to classes).
However, in Ruby, there are three kinds of variables, instance variables, class variables, class instance variables. See original post here.
-
Instance variables are prefixed by
@
, and available only inside instance methods. -
Class instance variables are prefixed by
@
, defined inside class directly, and available only inside class methods. The naming may sound strange, but it becomes sensible once realizingclass
is anobject
as well in Ruby. -
Class variables are prefixed by
@@
, and available in both instance methods and class methods.
1 | class Test |
There’s another important difference between class variables, and class instance variables. This SO
answer explains it really well: class instance variables
are local to the class instance (note that class
is an object
as well), while class variables are shared by all classes in the hierarchy chain. It
provides two snippets as well, which are reprinted below:
Class instance variables:
1 | class Parent |
Class variables:
1 | class Parent |