Ruby继承获取调用方类名
我太迷路了。我知道如何使用caller来获取caller方法,但是如何使用getthecaller类呢 例如:Ruby继承获取调用方类名,ruby,inheritance,Ruby,Inheritance,我太迷路了。我知道如何使用caller来获取caller方法,但是如何使用getthecaller类呢 例如: class Testing def return_caller_class return caller_class end end class Parent attr_accessor :test_me def initialize self.test_me = Testing.new end end class Child
class Testing
def return_caller_class
return caller_class
end
end
class Parent
attr_accessor :test_me
def initialize
self.test_me = Testing.new
end
end
class Child < Parent
end
class GrandChild < Child
end
test_Parent = Parent.new
test_Child = Child.new
test_GrandChild = GrandChild.new
puts test_Parent.test_me.return_caller_class => Parent
puts test_Child.test_me.return_caller_class => Child
puts test_GrandChild.test_me.return_caller_class => GrandChild
输出为:
{"
"=>Parent}
{"
"=>Child}
{"
"=>GrandChild}
为了更好地解释我的问题
我希望输出显示这个
Parent
Child
GrandChild
我对这个问题有点不了解,但我认为您犯了一些与获取调用方类名问题无关的错误。如果我能帮你做这些事情,至少你可以更进一步(如果有解决办法的话) 首先,在我看来,您是从主程序对象调用
return\u caller\u class
,而不是从您创建的三个对象之一调用的。在类父对象
中有一个类测试的对象
,但方法调用在这两个对象之外
第二,您似乎得到了接近您想要的东西的唯一原因(当您得到像“=>Parent}
这样的输出时)与返回调用方类
方法无关。似乎您无意中在程序的最后三行中创建了小哈希(当您添加=>Parent
等时),将其输出为put
(此处确认:)如果这些是注释,则需要在它们前面加一个#
另外,我在另一个线程上找到了指向此gem的链接:。可能值得检查。类测试
class Testing
def return_caller_class
self.class.name
end
end
class ChildOne < Testing
end
class ChildTwo < Testing
end
result:
------------------------------------------------
>ChildOne.new.return_caller_class
=> "ChildOne"
>ChildTwo.new.return_caller_class
=> "ChildTwo"
>Testing.new.return_caller_class
=> "Testing"
def return_caller_类
self.class.name
结束
结束
ChildOne类<测试
结束
第二类<测试
结束
结果:
------------------------------------------------
>ChildOne.new.return\u caller\u类
=>“ChildOne”
>ChildTwo.new.return\u caller\u类
=>“第二个孩子”
>Testing.new.return\u caller\u类
=>“测试”
看看谢谢,我现在就去看看。这个问题还没有解决。OP决定结束这个问题。您可能想将self to作为参数来使用determine The class,否则您可以使用一个模块并尝试使用,谢谢您的建议,但我使用的是类,而不是模块和参数er已经修复。感谢您指出我的假设哪里错了。我会检查那个链接。我尝试了返回方法(被调用方).owner,它返回'Testing;,我将查看更多信息。从该链接中,我可能会找到如何返回其他类名。我明天将继续我的研究。今天下午我遇到了一些问题,不得不暂停我的研究。谢谢gem运行得很好,但我不希望依赖gem,遗憾的是,在阅读了C库之后,我无法使用它N将其发布到ruby中,哦,好吧。哦,好吧,把它归结为一次学习体验,希望你能找到一种替代的、更惯用的ruby方法来完成你需要的。请简要解释一下为什么这段代码可以工作,没有解释的大代码转储可能会非常混乱这既不是大代码也不是混乱。这是自我体验拉那托里。
class Testing
def return_caller_class
self.class.name
end
end
class ChildOne < Testing
end
class ChildTwo < Testing
end
result:
------------------------------------------------
>ChildOne.new.return_caller_class
=> "ChildOne"
>ChildTwo.new.return_caller_class
=> "ChildTwo"
>Testing.new.return_caller_class
=> "Testing"