override a method on a subclass in ruby

To override a method on a subclass in Ruby, you can simply define the method with the same name in the subclass. When the method is called on an instance of the subclass, the subclass method will be executed instead of the superclass method.

Here is an example:

main.rb
class Animal
  def speak
    puts "Hello!"
  end
end

class Dog < Animal
  def speak
    puts "Woof!"
  end
end

dog = Dog.new
dog.speak # Output: "Woof!"
155 chars
15 lines

In this example, we define a superclass Animal with a speak method that prints "Hello!". We then define a subclass Dog that inherits from Animal and overrides the speak method with a new implementation that prints "Woof!". When the speak method is called on an instance of Dog, the subclass method is executed and "Woof!" is printed to the console.

gistlibby LogSnag