在define_method中调用super时没有超类方法

aus*_*ten 7 ruby

  • 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")
Run Code Online (Sandbox Code Playgroud)

MC2*_*2DX 5

它无法工作,因为您覆盖了#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")
Run Code Online (Sandbox Code Playgroud)

  • 他在写`#foo`,而不是覆盖`#foo`。 (2认同)