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")
Run Code Online (Sandbox Code Playgroud)
它无法工作,因为您覆盖了#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)
| 归档时间: |
|
| 查看次数: |
5769 次 |
| 最近记录: |