override a static method on a subclass in ruby

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.rb
class Animal
  def self.sound
    puts "A generic animal sound"
  end
end

class Dog < Animal
  def self.sound
    puts "Bark!"
  end
end

Animal.sound # Output: A generic animal sound
Dog.sound # Output: Bark!
211 chars
15 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.rb
class Cat < Animal
  def self.sound
    super
    puts "Meow!"
  end
end

Cat.sound # Output:
# A generic animal sound
# Meow!
127 chars
11 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