7
  • 为什么我talk: super: no superclass method talk (NoMethodError)在覆盖已存在的方法时会收到以下错误?
  • 如何修复此代码以调用超级方法?

这是我正在使用的示例代码

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")
4

1 回答 1

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")
于 2012-12-12T18:48:14.517 回答