Instance variable vs Class variables

Instance variables and class variables are two distinct types of variables in Ruby on Rails, each serving different purposes

Instance variables are associated with instances or objects of a class. They have a unique value for each instance of a class and are accessible only within the scope of that particular instance. Instance variables are typically prefixed with the '@' symbol. These variables are useful for storing data that needs to be specific to each instance of a class.

Here's an example to illustrate instance variables in Rails:

class Person
  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello, #{@name}!"
  end
end

person1 = Person.new("Alice")
person2 = Person.new("Bob")

person1.greet  # Output: Hello, Alice!
person2.greet  # Output: Hello, Bob!

In this example, the @name variable is an instance variable. Each instance of the Person class has its own @name value, allowing us to customize the greeting for each person.

On the other hand, class variables are associated with the entire class rather than with instances. They are prefixed with '@@' symbols and are shared among all instances of a class, including its subclasses. Class variables are useful when you need to maintain data that is shared across multiple instances.

Let's consider a simple example to demonstrate class variables:

class Circle
  @@count = 0

  def initialize(radius)
    @radius = radius
    @@count += 1
  end

  def self.total_count
    @@count
  end
end

circle1 = Circle.new(5)
circle2 = Circle.new(10)

puts Circle.total_count  # Output: 2

In this example, the @@count variable is a class variable that keeps track of the total number of Circle instances created. Whenever a new instance is initialized, the @@count value is incremented. The total_count method is defined as a class method to access the class variable.

To summarize, instance variables are specific to each instance of a class, whereas class variables are shared across all instances and subclasses of a class."

Last updated