Class Variables
Learn about class variables.
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:
class Employee@@no_of_employees = 0def initialize(name)@employee_name = name@@no_of_employees += 1enddef total_no_of_employees()puts "Total number of employees: #@@no_of_employees"endend# Create Objectse1 = Employee.new("Emma")e2 = Employee.new("David")e3 = Employee.new("Harris")# Call Methodse1.total_no_of_employees()e2.total_no_of_employees()e3.total_no_of_employees()
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.