* Global variables are stored globally, and local variables
are stored lexically, so neither of them is relevant to our discussion now, as
they do not interact with Ruby??™s class system.
Instance variables are specific to a certain object. They are prefixed with one @ symbol:
@price is an instance variable. Because every Ruby object has an iv_tbl structure,
any object can have instance variables.
Since a class is also an object, a class can have instance variables. The following code
accesses an instance variable of a class:
class A
@ivar = "Instance variable of A"
end
A.instance_variable_get(:@ivar) # => "Instance variable of A"
Instance variables are always resolved based on the object pointed to by self. Because
self is A??™s class object in the class A ... end definition, @ivar belongs to A??™s class object.
Class variables are different. Any instance of a class can access its class variables (which
start with @@). Class variables can also be referenced from the class definition itself.
While class variables and instance variables of a class are similar, they??™re not the same:
class A
@var = "Instance variable of A"
@@var = "Class variable of A"
def A.ivar
@var
end
def A.cvar
@@var
end
end
A.ivar # => "Instance variable of A"
A.cvar # => "Class variable of A"
In this code sample, @var and @@var are stored in the same place: in A??™s iv_tbl. However,
they are different variables, because they have different names (the @ symbols are
included in the variable??™s name as stored).
Pages:
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45