简体   繁体   中英

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

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

Or use modules:


module Parent

    def something
        something
    end
end

class Child

    inlude Parent

end

abc = Child.new
abc.something

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   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM