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

时间:2012-12-12 18:36:17

标签: 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")

1 个答案:

答案 0 :(得分: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")