Making Change Happen

Introducing a new twice yearly publication giving voice to the people working for social, societal and environmental progress. At Wolf&Player we are inspired everyday by the work of our partners. We…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Ruby Inheritance and Super

image source — GiraffeAcademy.com

Something that makes Ruby particularly useful is the ability to have classes share traits from one to another. It’s appropriately called “inheritance” as in something passed down from parent to child. One class can “inherit” or share the methods from a “parent” or what is more so known as a super-class.

Let’s look at this snippet below:

By using “<” we are essentially saying that our class “Dog” is inheriting from our “Pet” class. This is what establishes the parent-child relationship. Pet is passing all of its methods and attributes to Dog and Cat, but our child classes have their own properties such as breed.

So when we initialize a new pup:

So now we can save some space with the variables we want to attach to classes that share similar attributes and methods.

When we establish a “Super” class, we can also call the body of a method from the super-class into a method of the same name in a sub-class.

Let us make a method to feed our pets because all pets need to eat.

We will return:

The main benefit of using super is being able to use similar actions within a method with many classes while still adding unique actions to the sub-class method.

We could add to our Dog class method, something like:

Using inheritance can save you from repeating yourself in many cases when working with similar classes. It is worth practicing and trying different ideas out. Give it a shot and explore the benefits of Ruby Inheritance!

Add a comment

Related posts:

I Did Not See That Coming

He positioned the sparring bags like I was supposed to do a shin kick, even though I’m sure he instructed me to lift the leg and do a straight kick to the chest. My wires got crossed. Encouraging me…

Diversity is the Kingdom

Many academics have debated the definition of leadership. However, there is a plethora of scholarly research on leadership traits and theories that help aid one’s general understanding of the topic…

Haze

As I am writing these lines, several U.S. states have passed some of the strictest abortion restriction laws in the country. Alabama, Kentucky, Georgia…Reproductive rights are being challenged. Women…