Home > database >  How to access a parent method from a child class in Ruby?
How to access a parent method from a child class in Ruby?

Time:06-18

What is the right syntax to access a parent method from a child class in Ruby?

class Parent
    def initialize()
    end
    def p_do_something_1()
    end
    def p_do_something_2()
    end
    class Child
        def initialize()
        end
        def c_do_something_1()
        end
        p_do_something_1 = Parent.p_do_something_1() # What's the right way to do this?
    end
end

CodePudding user response:

Or use modules:


module Parent

    def something
        something
    end
end

class Child

    inlude Parent

end

abc = Child.new
abc.something

CodePudding user response:

Currently, Child is not actually inheriting from Parent because Ruby has a different syntax for inheritance. Once that is fixed you can call a method on the parent with the same name from the child with super.

class Parent
  def initialize()
  end

  def method()
    puts "from Parent"
  end
end

class Child < Parent # This means Child inherits from Parent
  def initialize()
  end
  
  def method  
    puts "from Child"
    super # calling the same method from Parent
  end
end

child = Child.new
child.method
#=> from Child
#=> from Parent   
  • Related