Learning Ruby Series 3 of 5

Ruby Class

A class is generally a collection of methods, and potential module(s). We learnt in the 2nd chapter of this series that multiple methods can be associated with an object. We also did a quick inspect of the hierarchy of the Ruby Object. The next evolution of this hierarchy is the Ruby class. Let us get back to experimenting in irb:

As we have discovered, variables are some of the most common features of a program. A class is no different. There are local, instance and occasionally class variables used. Mostly it is local and instance variables. Accessing these variables in a class can happen through get and set methods defined from first principles. Example:

Now that we have defined the class, and the methods to get and set names, let us continue with our experimentation

Let us explore the newly created instance “u” further

Luckily for us, ruby provides attr_* methods. This provides a cleaner and simpler way to code for access to variables.

Class Inheritance

Inheritance is a popular OOPs concept that involves transferring hierarchically the parent’s behavior to the inheriting child, with the child having the ability to override, retain, and / or add-on additional characteristics