如何确定定义方法的类? [英] How to determine the class a method was defined in?
本文介绍了如何确定定义方法的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态确定定义当前方法的类.
I would like to dynamically determine the class the current method was defined in.
这是我正在尝试做的静态示例:
Here's a static example of what I'm trying to do:
class A
def foo
puts "I was defined in A"
end
end
class B < A
def foo
puts "I was defined in B"
super
end
end
A.new.foo
# I was defined in A
B.new.foo
# I was defined in B
# I was defined in A <- this is the tricky one
如何用动态表达式替换上面字符串中的A
和B
?
How can I replace A
and B
in the strings above with a dynamic expression?
显然,#{self.class}
不起作用.(它会为 B
打印两次 I was defined in B
)
Apparently, #{self.class}
does not work. (it would print I was defined in B
twice for B
)
我怀疑答案是你不能",但也许我忽略了一些东西.
I suspect that the answer is "you can't", but maybe I'm overlooking something.
推荐答案
这个怎么样?
class A
def foo
puts "I was defined in #{Module.nesting.first}"
end
end
class B < A
def foo
puts "I was defined in #{Module.nesting.first}"
super
end
end
根据 WandMaker 的建议进行了更正.
Corrected following WandMaker's suggestion.
这篇关于如何确定定义方法的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文