有这样的代码:
执行puts A.new.a,会出现什么结果?
文档上说:object instance调用extend module会覆盖原有的方法([url]http://www.ruby-doc.org/core/classes/Object.html#M000337[/url])
按文档理解,这种extend module里面再调用super,应该就调用到B.a的方法了,而实际运行还是调用到了A.a方法。
也就是说它不是简单的覆盖,而是保留了同名方法作为super,这样就出现了诡异的输出结果。
class Base
def a
puts "base"
return "base"
end
end
module BaseExtend
def a
puts "base extend"
super
return "base extend"
end
end
class A < Base
def initialize
extend BaseExtend
end
def a
super
puts "a"
return "a"
end
end
执行puts A.new.a,会出现什么结果?
文档上说:object instance调用extend module会覆盖原有的方法([url]http://www.ruby-doc.org/core/classes/Object.html#M000337[/url])
按文档理解,这种extend module里面再调用super,应该就调用到B.a的方法了,而实际运行还是调用到了A.a方法。
也就是说它不是简单的覆盖,而是保留了同名方法作为super,这样就出现了诡异的输出结果。
Ruby方法调用解析
本文探讨了一段Ruby代码中关于类方法调用和super关键字的行为。通过实例展示了当使用extend引入模块并重定义方法时,super关键字指向的具体行为,并讨论了这一过程中预期与实际输出的不同。
930

被折叠的 条评论
为什么被折叠?



