我太迷路了。我知道如何使用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 < 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
谢谢!!!
编辑:
我试着做了以下
class Testing
def return_caller_class
return caller[0][/`.*'/][1..-2]
end
end
输出为:
{"
"=>Parent}
{"
"=>Child}
{"
"=>GrandChild}
为了更好地解释我的问题。
我希望输出显示这个而不是
Parent
Child
GrandChild
我对这个问题有点力不从心,但我认为您犯了一些与获取调用方类名问题无关的错误。如果我能帮你做这些事情,至少你可能会更近一步(如果有可能的话)!
首先,在我看来,您是从主程序对象调用return_caller_class
,而不是从您创建的三个对象之一调用。在Parent
类的对象中有一个Testing
类的对象,但方法调用在两者之外。
其次,你似乎得到了接近你想要的东西的唯一原因(当你得到像"=>Parent}
这样的输出时)与return_caller_class
方法无关。你似乎无意中在程序的最后三行中创建了小散列(当你添加=> Parent
等时),这些散列是用puts
输出的。(此处确认:#puts是否创建了一个新的哈希?)如果这些是注释,那么它们之前需要一个#
。
PS。我在另一个帖子上找到了这个宝石的链接:https://github.com/asher-/sender.也许值得一看。
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"