Understanding Ruby Classes: Constructors and Methods
Revisiting Ruby Classes
Let's continue working with classes using a Robot example to explore how Ruby classes serve as blueprints for creating objects. Here's a basic class definition:
At this stage, the Robot class is like an empty shell. It exists but doesn't know how to do anything. To make it functional, it needs attributes and methods.
Deep Dive into Constructors
A constructor is a special method that initializes an object when it's created. In Ruby, the constructor is the method named initialize. It sets up—or constructs—our new objects with the necessary initial states.
Here, we upgrade the Robot class with a constructor:
In this case, the initialize method gets automatically called when we create a new Robot instance, setting the name and color attributes. It's always good practice to use constructors like initialize to ensure each instance starts with the correct initial values.
Multiple Constructors with Default Parameters
Having one constructor is great, but what if we want more flexibility in setting up our robots? In Ruby, we can provide default values for parameters to offer similar functionality.
Here's a default color for our robots:
With default parameters, color becomes optional. When we don't specify it, the robot is 'grey' by default.
Class Methods
Class methods provide additional behaviors for our objects, acting like commands that define how objects interact and perform actions.
This Robot class allows the robots to introduce themselves:
The say_hello method allows our robot instance to interact and even communicate.
