2014-01-15 39 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