Photo by Dayne Topkin on Unsplash

Overriding private methods of the superclass in Ruby

What happens when a private method of the superclass is overridden in Ruby?

Tech - RubyCademy
Published in
2 min readNov 18, 2020

--

As Ruby is an OOP language, a class can inherit from another one. In Ruby, the inherited class is commonly referred to as superclass — This name comes from the Class#superclass method that returns the directly inherited class of the receiver

Here, Parent defines the role method. Child that directly inherits from Parent, can call this method. This is due to the Method Lookup Path mechanism.

Feel free to read the Ruby Object Model article if you’re not familiar with this mechanism

Inheritance and private methods

In Ruby, a private method is a method that can only be called with an implicit receiver — or with self as a receiver since Ruby 2.7.

In this area, the self refers to the eigenclass (a.k.a the shadow class.)

Here, the role private method is accessible in the inheriting Child class. So the state of an inherited method is kept through inheritance.

Now, what happens if we override the role private method?

Overriding a private method

Here, Child class overrides Parent#role private method. In this case, we can see that role is defined as a public method after this overriding. Also, private_methods does not include #role even though this method is private in the ancestor chain of Child — through Parent#role method.

Indeed, private_methods knows that Child defines a role method. and as Child is the first entry of the ancestor chain (and the message handler during Method Lookup Path for a call to Child#role), it’ll be considered as the right version of #role to check by *_methods routines. So as Child#role isn’t defined as private, the private state of Parent#role isn’t inherited by Child#role.

Conclusion

So, always be careful when overriding methods defined with specific access control. Indeed, this state won’t be shared amongst the different versions of your method.

Ruby Mastery

We’re currently finalizing our first online course: Ruby Mastery.

Join the list for an exclusive release alert! 🔔

🔗 Ruby Mastery by RubyCademy

Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.

💚

--

--