Ruby Class Variables

Stewart Nguyen Mar 25, 2022
Ruby Class Variables

Global variables, instance variables, class variables, local variables, and constants are the five types of variables supported by Ruby. This article will focus on the class variables in Ruby.

Create Class Variables in Ruby

Class variables begin with @@. Like other variables, class variables must be defined before they can be used.

This example demonstrates creating a class variable using Ruby version 2.7.2.

Example:

class Foo
  @@var_1 = 1

  def show_class_variable
    "Value of @@var_1: #{@@var_1}"
  end

  def increase_value
    @@var_1 += 1
  end
end

Foo.new.show_class_variable

Output:

"Value of @@var_1: 1"

All instances of the class share the value of a class variable. If one object modifies the class variable, the value is applied to all objects of the same class.

Consider the following scenario, which uses the Foo class.

Example:

foo_1 = Foo.new
foo_2 = Foo.new

foo_1.show_class_variable
=> "Value of @@var_1: 1" #Output

foo_2.show_class_variable
=> "Value of @@var_1: 1" #Output

foo_1.increase_value
foo_2.show_class_variable
=> "Value of @@var_1: 2" #Output

Related Article - Ruby Variable