• 当我覆盖已经存在的方法时,为什么会收到以下错误talk: super: no superclass method talk (NoMethodError)
  • 如何解决此代码以调用super方法?

  • 这是我正在使用的示例代码
    class Foo
      def talk(who, what, where)
        p "#{who} is #{what} at #{where}"
      end
    end
    
    Foo.new.talk("monster", "jumping", "home")
    
    class Foo
      define_method(:talk) do |*params|
        super(*params)
      end
    end
    
    Foo.new.talk("monster", "jumping", "home")
    

    最佳答案

    它不起作用,因为您覆盖了#talk。尝试这个

    class Foo
      def talk(who, what, where)
        p "#{who} is #{what} at #{where}"
      end
    end
    
    Foo.new.talk("monster", "jumping", "home")
    
    class Bar < Foo
      define_method(:talk) do |*params|
        super(*params)
      end
    end
    
    Bar.new.talk("monster", "table", "home")
    

    关于ruby - 在define_method中调用super时没有父类(super class)方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13846339/

    10-13 02:37