class C1
def pr
puts 'C1'
end
end
class C2 < C1
def pr
puts 'C2'
super
puts self.method(:pr).source_location
end
end
c = C2.new
c.pr
在上面的程序中,是否有可能获取 super
(在我们的例子中为 C1::pr
)执行的代码的位置,以及我们获取C2::pr
代码使用 source_location
方法?
最佳答案
从 ruby 2.2 开始,您可以像这样使用 super_method
:
Class A
def pr
puts "pr"
end
end
Class B < A
def pr
puts "Super method: #{method(:pr).super_method}"
end
end
由于 super_method
返回一个方法,您可以将它们链接起来以查找祖先:
def ancestor(m)
m = method(m) if m.is_a? Symbol
super_m = m.super_method
if super_m.nil?
return m
else
return ancestor super_m
end
end
关于ruby - 如何找到super执行的代码的source_location?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16283428/