Calling method in parent class from subclass methods in Ruby

前端 未结 5 451
粉色の甜心
粉色の甜心 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:27

    If the method is the same name, i.e. you're overriding a method you can simply use super. Otherwise you can use an alias_method or a binding.

    class Parent
      def method
      end
    end
    
    class Child < Parent
      alias_method :parent_method, :method
      def method
        super
      end
    
      def other_method
        parent_method
        #OR
        Parent.instance_method(:method).bind(self).call
      end
    end
    

提交回复
热议问题