What is instance and class variable in Ruby?

As a developer, you're probably familiar with the object-oriented programming (OOP) concepts on which Ruby is built. In Ruby, instance and class variables are essential components of OOP, and understanding their differences and uses is critical to writing clean and maintainable code. In this article, we'll explore what instance and class variables are in Ruby and how they behave in the context of a class.

Instance Variables

Instance variables in Ruby are denoted by the @ symbol followed by the variable name. These variables are unique to each instance of a class and hold specific data relevant to that instance. Let's look at an example:

class MyClass
  @instance_var = 10

  def read
    p "instance_var: #{@instance_var}"
  end
end

obj1 = MyClass.new
obj1.read # => 10

In this code, @instance_var is an instance variable of the MyClass class. When we create an instance of MyClass using obj1, it has its own instance variable, and changing this variable in one instance won't affect other instances of the class.

Class Variables

Class variables in Ruby are denoted by two @ symbols followed by the variable name (e.g., @@class_var). Unlike instance variables, class variables are shared by all instances of a class. They store data that is shared by all instances of the class. Here's an example:

class MyClass
  @instance_var = 10
  @@class_var = 11

  def self.read
    p "instance_var: #{@instance_var}"
    p "class_var: #{@@class_var}"
  end

  def read
    p "instance_var: #{@instance_var}"
    p "class_var: #{@@class_var}"
  end
end

MyClass.read
# => "instance_var: 10"
# => "class_var: 11"
MyClass.new.read
# => "instance_var: "
# => "class_var: 11"

Class variables in Ruby are denoted by two @ symbols followed by the variable name (e.g., @@class_var). Unlike instance variables, class variables are shared by all instances of a class. They store data that is shared by all instances of the class. To access instance and class variables, you can use the @ symbol for instance variables and @@ for class variables within class methods and instance methods. In the code example provided, we can access both types of variables in the Read method, which is defined as both a class method and an instance method.

Conclusion

In Ruby, instance and class variables play important roles in object-oriented programming. Instance variables are unique to each instance of a class, while all instances share class variables. By using them effectively, you can create well-structured and maintainable Ruby code. Remember to use @ for instance variables and @@ for class variables, and consider the scope and purpose of each when designing your Ruby applications.