In this section, we will delve into class variables and methods in Ruby. Understanding these concepts is crucial for mastering object-oriented programming in Ruby.
Class Variables
Class variables are variables that are shared among all instances of a class. They are prefixed with @@ and are used to store information that is common to all objects of a class.
Key Points:
- Class variables are shared across all instances of a class.
- They are defined using
@@followed by the variable name. - Class variables can be accessed and modified by class methods and instance methods.
Example:
class Car
@@number_of_cars = 0
def initialize(model)
@model = model
@@number_of_cars += 1
end
def self.total_cars
@@number_of_cars
end
end
car1 = Car.new("Toyota")
car2 = Car.new("Honda")
puts Car.total_cars # Output: 2Explanation:
@@number_of_carsis a class variable that keeps track of the number ofCarinstances.- The
initializemethod increments@@number_of_carseach time a newCarobject is created. self.total_carsis a class method that returns the value of@@number_of_cars.
Class Methods
Class methods are methods that are called on the class itself, rather than on instances of the class. They are defined using self. followed by the method name.
Key Points:
- Class methods are called on the class itself, not on instances.
- They are defined using
self.before the method name. - Class methods can access class variables and other class methods.
Example:
class Car
@@number_of_cars = 0
def initialize(model)
@model = model
@@number_of_cars += 1
end
def self.total_cars
@@number_of_cars
end
def self.create_cars(models)
models.each { |model| Car.new(model) }
end
end
Car.create_cars(["Toyota", "Honda", "Ford"])
puts Car.total_cars # Output: 3Explanation:
self.create_carsis a class method that takes an array of models and creates a newCarobject for each model.Car.create_cars(["Toyota", "Honda", "Ford"])creates threeCarobjects.Car.total_carsreturns the total number ofCarobjects created, which is 3.
Practical Exercises
Exercise 1: Implementing Class Variables and Methods
Task:
Create a Library class that keeps track of the total number of books and allows adding new books.
Solution:
class Library
@@total_books = 0
def initialize(name)
@name = name
@books = []
end
def add_book(book)
@books << book
@@total_books += 1
end
def self.total_books
@@total_books
end
end
library1 = Library.new("City Library")
library2 = Library.new("County Library")
library1.add_book("1984")
library2.add_book("Brave New World")
library2.add_book("Fahrenheit 451")
puts Library.total_books # Output: 3Explanation:
@@total_booksis a class variable that keeps track of the total number of books across all libraries.add_bookis an instance method that adds a book to the library and increments@@total_books.self.total_booksis a class method that returns the total number of books.
Common Mistakes:
- Forgetting to use
self.for class methods: Ensure you prefix class methods withself.. - Misusing class variables: Remember that class variables are shared across all instances, so changes in one instance affect all others.
Conclusion
In this section, we covered class variables and methods in Ruby. We learned how to define and use class variables to store information shared among all instances of a class. We also explored class methods, which are called on the class itself and can access class variables. Understanding these concepts is essential for effective object-oriented programming in Ruby. In the next section, we will explore inheritance, which allows us to create hierarchical class structures.
Ruby Programming Course
Module 1: Introduction to Ruby
Module 2: Basic Ruby Concepts
Module 3: Working with Collections
Module 4: Object-Oriented Programming in Ruby
- Classes and Objects
- Instance Variables and Methods
- Class Variables and Methods
- Inheritance
- Modules and Mixins
Module 5: Advanced Ruby Concepts
Module 6: Ruby on Rails Introduction
- What is Ruby on Rails?
- Setting Up Rails Environment
- Creating a Simple Rails Application
- MVC Architecture
- Routing
Module 7: Testing in Ruby
- Introduction to Testing
- Unit Testing with Minitest
- Behavior-Driven Development with RSpec
- Mocking and Stubbing
