To add a static method to a Ruby subclass, you can use the self
keyword in the method definition to create a class-level method. Here's an example of how to do this:
main.rb461 chars16 lines
In the example above, we've defined a static_method
on the Parent
class using the self
keyword in the method definition. When we call Parent.static_method
, it will execute the method and print out the message.
We've also created a Child
subclass of Parent
, and added another static method called another_static_method
. When we call Child.another_static_method
, it will print out a different message.
Note that both the Parent
class and the Child
subclass can call the static_method
, but only the Child
class can call the another_static_method
. This is because another_static_method
is defined only on the Child
class, not on the Parent
class.
gistlibby LogSnag