2014-01-15 38 views
1

我很迷茫。我知道如何使用调用者来获取调用者方法,但是你怎样使用调用者类呢?Ruby继承获取来电者类名

例如:

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 
+0

看看https://www.ruby-forum.com/topic/161460 – bjhaid

+0

谢谢,我现在检查一下。 – user3163916

+0

虽然这个问题没有解决。 OP决定结束这个问题。 – user3163916

回答

2

我有点出我的深度与这个问题,但我想你已经无关获得调用者的类的问题了几个错误名称。如果我可以帮助你解决这些问题,至少你可能会更近一步(如果解决方案甚至可能的话)!

首先,在我看来,你从主程序对象调用return_caller_class,而不是从你创建的三个对象之一调用。在类Parent的对象内部有类Testing的对象,但方法调用在两者之外。

其次,你似乎有什么东西接近你想要的东西的唯一原因(当你得到像"=>Parent}这样的输出与return_caller_class方法没有任何关系时,看起来好像你无意中在最后三行中创建了很小的哈希值你的程序的(当你添加=> Parent等),目前正在输出与puts(这里确认:Has #puts created a new hash?)。如果这些都意味着是意见,他们需要一个#之前

PS我找到了一个链接。到另一个线程上的这个宝石:https://github.com/asher-/sender。可能值得一试。

+0

感谢您指出我错误的地方。我会检查这个链接。 – user3163916

+0

我试过返回方法(__ callee __)。owner,它返回'Testing;我会检查更多信息。从那个环节。我可能会发现如何返回其他类名。 – user3163916

+0

明天继续我的研究。今天下午我得到了一些东西,我不得不暂停研究。 – user3163916

-1
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" 
+3

请简要说明为什么此代码可以正常工作,没有解释的大代码转储可能会让您感到困惑 – Jeeter

+0

这既不是大代码也不会让人困惑。这是自我解释。 – Lezard