ruby class variable

Ruby Class Variables

In Ruby, class variables are variables that are shared among all instances of a class. They are prefixed with @@ and are declared within the class body but outside of any method. Here are the steps to use class variables in Ruby:

  1. Declare a class variable using the @@ prefix.
  2. Assign a value to the class variable within the class body.
  3. Access the class variable within the class or its instances.

Here's an example that demonstrates the usage of class variables in Ruby:

class MyClass
  @@count = 0

  def initialize
    @@count += 1
  end

  def self.get_count
    @@count
  end
end

obj1 = MyClass.new
obj2 = MyClass.new

puts MyClass.get_count # Output: 2

In the example above: - Step 1: The class variable @@count is declared within the MyClass class. - Step 2: The class variable @@count is incremented by 1 each time a new instance of MyClass is created. - Step 3: The class method get_count is defined to access the value of the class variable @@count.

When the code is executed, the output will be 2 because two instances of MyClass were created.

Please note that class variables in Ruby have some limitations and considerations, such as scoping rules and potential issues with inheritance. It's important to understand these nuances when using class variables in your Ruby code.

[[SOURCE 6]]