To override a static method, also known as a class method, on a subclass in Ruby, you can simply define a new method with the same name on the subclass. When the method is called on the subclass, the new implementation will be used instead of the one inherited from the parent class.
Here's an example:
main.rb211 chars15 lines
In the example above, both classes have a sound
method. When called on the parent Animal
class, it outputs a generic animal sound. However, when called on the Dog
subclass, it outputs "Bark!", which is the new implementation defined in the subclass.
Note that when you override a method in a subclass, you can still access the original implementation using the super
keyword.
main.rb127 chars11 lines
In this case, the Cat
class calls super
to execute the sound
method defined in the parent Animal
class. It then adds its own implementation to output "Meow!". This way, you can use the original implementation as a base and make modifications on top of it.
gistlibby LogSnag