2012-12-12 38 views
4
  • 爲什麼我會覆蓋以下錯誤talk: super: no superclass method talk (NoMethodError)當我重寫已存在的方法?
  • 我該如何解決這個代碼來調用超級方法?

這裏是我使用在define_method中調用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") 
+0

見http://stackoverflow.com/questions/4470108/when-monkey-patching-a-method-can-you-call-the-overridden-method-from-the-new-i/44712​​02#44712​​02 –

回答

4

它不工作,因爲你覆蓋#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") 
+2

他正在編寫'#foo'而不是重寫'#foo'。 –

+0

我的意思是'#talk',而不是'#foo'。 –

+0

謝謝。我的大腦不能正常工作。我認爲這與我使用'define_method'的方式有關。 – austen

相關問題