add a method to a subclass in ruby

To add a method to a subclass in Ruby, you can define the method in the subclass itself. Here's an example:

main.rb
class ParentClass
  def parent_method
    puts "This is a method in the parent class"
  end
end

class ChildClass < ParentClass
  def child_method
    puts "This is a method in the child class"
  end
end

child_instance = ChildClass.new
child_instance.parent_method  # Output: This is a method in the parent class
child_instance.child_method   # Output: This is a method in the child class
390 chars
16 lines

In this example, we have a ParentClass that has its own method parent_method. We then define a ChildClass that inherits from the ParentClass using <. The ChildClass also has its own method child_method.

To add a method to the ChildClass, we simply define the method within the ChildClass block like we did with child_method. Now instances of the ChildClass can use both the methods from the ParentClass and the ChildClass itself.

In the example, we create an instance of the ChildClass and call both the parent_method and child_method using the instance.

gistlibby LogSnag