Classes and Objects in Ruby
Classes and Objects
Let's dive into a foundational concept in Object-Oriented Programming (OOP): Classes and Objects. If you have already explored OOP concepts in other programming languages or previous units, this might serve as a good reminder. If not, no worries, we'll start from the basics.
Classes and objects are the building blocks of OOP. A class acts as a blueprint for creating objects, which are instances of the class. Understanding these basics is essential before moving on to more advanced OOP topics like inheritance, polymorphism, and encapsulation.
What You'll Learn
In this lesson, you'll learn how to define and use classes and objects in Ruby. We'll cover:
- Declaring and Defining Classes
- Creating Objects from Classes
- Using Constructors
Declaring and Defining Classes
In Ruby, a class is defined using the class keyword, and the constructor is defined with the initialize method. Here's a simple example:
In this snippet, we define a Person class with instance variables @name and @age and a method, display, which prints the object's data. Unlike in some other languages, Ruby does not require the explicit specification of data member accessibility (private), and we typically use instance variables prefixed with @.
Creating Objects from Classes
Once you have defined a class, you can create objects (instances of the class). Here’s how we can create and use objects of the Person class:
Here, we create an object, person, with the name "Alice" and age 30, and call the display method to print the object's data directly. Ruby uses new for object creation, which automatically invokes the initialize method.
Instance variables belong to the instance of the class and retain their values as long as the object exists. They are not shared across instances, which means every object of the class will have its own separate @name and @age. This is a key feature in Ruby that supports encapsulation, allowing data to be tied directly to the instance.
Without initialize, object creation would still work, but no initial setup (like assigning @name and @age) would occur.
