Calling method in parent class from subclass methods in Ruby

前端 未结 5 476
粉色の甜心
粉色の甜心 2020-12-24 05:20

I\'ve used super to initialize parent class but I cannot see any way of calling parent class from subclass methods.

I know PHP and other languages do ha

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-24 05:49

    class Parent
      def self.parent_method
        "#{self} called parent method"
      end
    
      def parent_method
        "#{self} called parent method"
      end
    end
    
    class Child < Parent
    
      def parent_method
        # call parent_method as
        Parent.parent_method                # self.parent_method gets invoked
        # call parent_method as
        self.class.superclass.parent_method # self.parent_method gets invoked
        super                               # parent_method gets invoked 
        "#{self} called parent method"      # returns "# called parent method"
      end
    
    end
    
    Child.new.parent_method  #This will produce following output
    Parent called parent method
    Parent called parent method
    # called parent method
    #=> "# called parent method"
    

    self.class.superclass == Parent #=> true

    Parent.parent_method and self.class.superclass will call self.parent_method(class method) of Parent while super calls the parent_method(instance method) of Parent.

提交回复
热议问题