Ruby 当从子方法调用父方法时,从父方法调用子方法

Ruby 当从子方法调用父方法时,从父方法调用子方法,ruby,Ruby,有两个Ruby类: class Parent class << self def method1 ... end def method2 ... method1 ... end end end class Child < Parent class << self def method1 ... end def method2

有两个Ruby类:

class Parent
  class << self
    def method1
      ...
    end

    def method2
      ...
      method1
      ...
    end
  end
end

class Child < Parent
  class << self
    def method1
      ...
    end

    def method2
      ...
      super
    end
  end
end
类父类

类所以我用一些put运行了您的代码:

class Parent
  class << self
    def method1
        puts "parent.method1; self: #{self.inspect}"
    end

    def method2
        puts "parent.method2 before method1 call; self: #{self.inspect}"
        method1
        puts "parent.method2 after method1 call"
    end
  end
end

class Child < Parent
  class << self
    def method1
        puts "child.method1; self: #{self.inspect}"
    end

    def method2
        puts "child.method2 before super; self: #{self.inspect}"
        super
        puts "child.method2 after super"
    end
  end
end


Child.method2
这不是你想要的吗


Ruby处理方法解析,目标始终是对象的类。在上面的代码中,即使使用super调用,该类仍然是子类。因此,它将调用在child上定义的任何方法,如果找不到,则调用parent,或者如果child调用super…

谢谢您的详细回答。这很遗憾,但有时我最初的结果会有所不同。
child.method2 before super; self: Child
parent.method2 before method1 call; self: Child
child.method1; self: Child
parent.method2 after method1 call
child.method2 after super