Object Oriented Programming in Ruby
Everything in Ruby is an object, and that means that everything in Ruby shares certain behaviours. These behaviours are the four aspects of Object Oriented Programming. They are called Abstraction, Inheritance, Polymorphism and Encapsulation.
Abstraction
Abstraction is the process of making something easier to understand by ignoring details that are unimportant and defining the things that are. In Ruby we do this by creating classes and specifying the qualities that they have and therefore the actions that we want them to take. Imagine you are the director of a birdwatching club in New Zealand. You are concerned with the identifying birds based on their plumage, their call and their habits. You could model them as a Class called Bird. The Bird class will be well defined so that we have only the relevant qualities of what identifies a bird. We don’t need to include any information what a bird eats or what their eggs look like. Let’s start by simply defining a general bird.
Inheritance
Inheritance is the relationship between a child class and its parent. A child class inherits all the features of its parent class, but can also override certain features as well as have its own unique attributes. In Ruby a class can only inherit from a single other class. For instance, a tui, a kākāpō, a pīwakawaka and a korimako are all belong to the class Bird, but have qualities that make them different birds to the others.
Polymorphism
Polymorphism comes from Greek, meaning “many forms”. In Ruby it specifically means the ability to send the same message (through methods) to different objects and get different results.
You might have noticed in the example above how each bird inherits from the class Bird, but each bird has a different output when asked for information about their call and plumage. All inherit the fly method unchanged, except the kakapo, a flightless parrot.
In essence all birds inherit from the Bird class but each can modify the attributes it passes them to suit their specifications.
Encapsulation
Encapsulation is hiding implementation details of a class from other objects. In essence, the Birdwatching Club Director simply wants to identify birds, based on their appearance and call. We can pack all of the information that we need to identify a bird into a single component and hide how it works. This is important so that the function works as we expect, and others using our classes cannot mess how they work. We hide the internal data by making it private
. Now the identify
method can access its own data but another object using the method cannot. Encapsulation decreases complexity by ensuring the internal components of an object are hidden from the outside.