Difference between class variable and instance variable in Ruby


It is used to keep track of objects; each variable holds a reference to an object.

[ruby]person = “Tim”
puts “The object in ‘person’ is a #{person.class}”
puts “The object has an id of #{person.object_id}”
puts “and a value of ‘#{person}'”
[ruby]The object in ‘person’ is a String
The object has an id of 338010
and a value of ‘Tim’

On the first line, Ruby creates a new String object with the value, Tim. A reference to this object is placed in the local variable person. A quick check shows that the variable has indeed taken on the personality of a string, with an object ID, a class, and a value.

So, is it a variable an object? In Ruby, the answer is “no.” A variable is simply a reference to an object. Objects float around in a big pool somewhere (the heap, most of the time) and are pointed to by variables.

[ruby]person1 = “Tim”
person2 = person1
person1[0] = ‘J’
puts “person1 is #{person1}”
puts “person2 is #{person2}”

[ruby]person1 is Jim
person2 is Jim

Class Variable vs Instance Variable:

In your Square class you defined two methods: initialize and area. Both are instance methods, as they relate to, and operate directly on, an instance of an object. Here’s the code again:

[ruby]class Square
def initialize(side_length)
@side_length = side_length
def area
@side_length * @side_length

Once you’ve created a square with s = Square.new(10) , you can use s.area to get back the area of the square represented by s. The area method is made available in all class square objects, so it’s considered an instance method .

However, methods are not just useful to have available on object instances. It can be useful to have methods that work directly on the class itself. In the previous section you used a class variable to keep a count of how many square objects had been created, and it would be useful to access the @@number_of_squares class variable in some way other than through Square objects. Here’s a simple demonstration of a class method:

[ruby]class Square
def self.test_method
puts “Hello from the Square class!”
def test_method
puts “Hello from an instance of class Square!”
Square. new.test_method