Ruby - Class Methods and Variables

1. Introduction

Ruby provides a mechanism for defining class methods and variables which are shared across instances of a class. This post explores the concept of class methods and class variables in Ruby, and how they differentiate from instance methods and instance variables.

Class Methods and Class Variables Overview

1. Class Methods: These are methods that are called on the class itself, not on instances of the class. They are defined using self.method_name or ClassName.method_name within the class definition.

2. Class Variables: These are variables that maintain a single shared value for all instances of a class. They are prefixed with @@ and are accessible throughout the class, including in instance methods.

2. Program Steps

1. Define a class.

2. Inside the class, initialize class variables (if any).

3. Define class methods using self.method_name.

4. Instantiate objects of the class.

5. Access and manipulate class variables and call class methods.

3. Code Program

# Define the class
class Car
  # Initialize a class variable to keep track of the total number of cars created
  @@total_cars = 0
  def initialize
    # Increment the class variable by one whenever a new car is created
    @@total_cars += 1
  end
  # Class method to display the total number of cars created
  def self.total_cars
    @@total_cars
  end
end
# Create instances of the Car class
car1 = Car.new
car2 = Car.new
# Call the class method on the Car class to get the total number of cars created
puts "Total number of cars: #{Car.total_cars}"

Output:

Total number of cars: 2

Explanation:

1. We define a Car class.

2. Inside the Car class, we initialize a class variable @@total_cars to 0. This variable will be used to keep track of the total number of car instances created.

3. The initialize method increments the @@total_cars variable by one every time a new Car object is instantiated.

4. A class method, total_cars, is defined using self.total_cars. This method returns the current value of the @@total_cars class variable.

5. We create two instances of the Car class using Car.new.

6. Lastly, we call the total_cars class method on the Car class to display the total number of car instances created.

Class methods and variables allow for shared behavior and data across instances, providing a means to operate on data that's relevant to the class as a whole, rather than individual instances.


Comments