Object Oriented Programming
Class and Instance Variables in Ruby
Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.
Syntax
$variableName #global scope
@@classVariable #class scope, static across all class instances
@instanceVariable #class object scope, value specific to object instance
#class variable getter, called on the class itself (hence self keyword)
def self.getClassVar
@@classVariable
end
#Ruby has shortcuts for instance variable getters and setters
#both getter and setters
attr_accessor :instanceVariable
#getter
attr_reader :instanceVariable
#setter
attr_writer :instanceVariable
Notes
Class and instance variables are private , so getters and setters are necessary to access the variables outside the class.
Instance variables are not inherited.
Example
class Car
@make
@@wheels = 4
def initialize(make)
@make = make
end
def self.wheels
@@wheels
end
attr_accessor :make
end
#outside the class
civic = Car.new("Honda")
#instance variable, called on the object
>>civic.make
=>"Honda"
#class variable, called on the class itself
>>Car.wheels
=>4