Instance variables are defined at the moment when a class has been instaniated. Suppose you have a class Point
, which define some local variables and methods.
class Point
def initialize(x,y)
@x, @y = x, y
end
def add(other)
Point.new(@x + other, @y + other)
end
end
When you instantiate the defined class and assign it to a variable you are instantiating the class:
point = Point.new(2,2)
..this is the instance variable.
Classes in Ruby are Objects and can have instance variables as other objects can. An instance variable defined inside a class
definition, but outside an instance method definition is called class instance variable.
Example:
class Point
@n = 0
@total_x = 0
@total_y = 0
def initialize(x,y)
@x,@y = x,y
end
end
There is a third one, namely the class variable
. Class variables are visible to, and shared by the class methods and the instance methods of the class. Like instance variables, class variables can be used by the implementation of a class, but they are not visible to the users of the class. Class variables begin with @@
. Instance variables are always evaluated in reference to self
. This is a significant difference from class variables, which are always evaluated in reference to the class object created by the enclosing class
definition statement. Using the same example we can rewrite the code as follows:
class Point
@@n = 0
@@total_x = 0
@@total_y = 0
def initialize(x,y)
@x,@y = x, y
@@n += 1
end
def self.report
puts "Number of points: #{@@n.to_s}"
end
end