1.4 Knowing Your Inheritance

Know those sub-classes

The final lifecycle callback is the Class#inherited method, which is invoked whenever a given Class is sub-classed. It receives exactly one parameter, which is the sub-class (again, not the name of the sub-class, but rather the sub-class itself).

Here's an exercise so you can get your feet wet.


Implement inherited as a self method on Room and store the parameter it receives in @@subclasses.

Output Window

And we're done

With this, we're done with Ruby's Object Lifecycle Callbacks. Use them sparingly, use them well.

Here's a final exercise to keep them fresh in your mind. It's based on a common pattern seen in many Ruby gems. All you should do is add the lifecycle callbacks containing code necessary to make the tests pass.


Add an included callback to Gym that in turn includes Gym::InstanceMethods into the target class and extends the target with Gym::ClassMethods.

Output Window

Congratulations, guest!

% of the book completed


This lesson is Copyright © 2011-2024 by Sidu Ponnappa and Jasim A Basheer