Class Variables
Explore how to work with class variables in Ruby, which start with @@ and are shared across all instances within a class. Understand how to initialize class variables, track shared data like employee counts, and access them from any part of the class. This lesson helps you manage data that belongs to the whole class effectively.
We'll cover the following...
Class variables
A class variable’s name starts with a @@ sign. It must be initialized before use. Its scope is limited to the class in which it’s created. In other words, it belongs to the whole class and can be accessed from anywhere in the class.
For example:
Explanation
-
The
@@no_of_employeesclass variable tracks the count of the number of existing instances of theEmployeeclass. -
Whenever a new
Employeeinstance is instantiated by a call toEmployee.new, the name of that employee is stored in the@employee_nameinstance variable, and the total count is increased by adding1to the@@no_of_employeesclass variable in line 5. -
Three new instances of the
Employeeclass are created in lines 14–16. This is why each instance has a different value assigned to the@employee_nameinstance variable. Notice, though, how all three employees know (on lines 19–21) that there are three employees.