Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Ruby Foundations | 19

Variable Lookup


There are four types of variables in Ruby: global variables, class variables, instance
variables, and local variables.*Global variables are stored globally, and local vari-
ables 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@sym-
bol:@priceis an instance variable. Because every Ruby object has aniv_tblstruc-
ture, 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 byself. Because
self isA’s class object in theclass A...end definition,@ivar belongs toA’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,@varand@@varare stored in the same place: inA’siv_tbl. How-
ever, they are different variables, because they have different names (the@symbols are
included in the variable’s name as stored). Ruby’s functions for accessinginstancevari-
ables and class variables check to ensure that the names passed are in the proper format:


A.instance_variable_get(:@@var)
# ~> -:17:in `instance_variable_get': `@@var' is not allowed as an instance
variable name (NameError)


  • There are also constants, but they shouldn’t vary. (They can, but Ruby will complain.)

Free download pdf