0
0
Rubyprogramming~5 mins

Class instance variables as alternative in Ruby

Choose your learning style9 modes available
Introduction

Class instance variables let you store data that belongs to the class itself, not to each object made from it. This helps keep shared information organized and separate from individual objects.

When you want to keep track of data shared by all objects of a class, like a count of how many objects were created.
When you want to store settings or configuration that applies to the whole class.
When you want to avoid using global variables but still share data across all instances.
When you want to keep class-level data private and not accessible from outside the class.
Syntax
Ruby
class ClassName
  @class_instance_variable = value

  def self.class_instance_variable
    @class_instance_variable
  end
end

Class instance variables start with @ but are defined inside the class, outside any method.

To access them, you usually define class methods (using self.) that read or write these variables.

Examples
This example uses a class instance variable @count to count how many Dog objects are created.
Ruby
class Dog
  @count = 0

  def self.count
    @count
  end

  def initialize
    self.class.instance_variable_set(:@count, self.class.count + 1)
  end
end
This example shows a class instance variable @wheels storing a value shared by the class Car.
Ruby
class Car
  @wheels = 4

  def self.wheels
    @wheels
  end
end

puts Car.wheels  # prints 4
Sample Program

This program counts how many Book objects are created using a class instance variable @total_books. Each time a new Book is made, the count increases by one.

Ruby
class Book
  @total_books = 0

  def self.total_books
    @total_books
  end

  def initialize(title)
    @title = title
    self.class.instance_variable_set(:@total_books, self.class.total_books + 1)
  end
end

book1 = Book.new("Ruby Basics")
book2 = Book.new("Learn Programming")

puts "Total books created: #{Book.total_books}"
OutputSuccess
Important Notes

Class instance variables are different from class variables (@@var) because they belong only to the class, not to subclasses.

Use class methods to safely access or change class instance variables.

Summary

Class instance variables store data for the class itself, not for each object.

They help keep shared data organized and private to the class.

Access them through class methods to read or update their values.