2017-01-08 47 views
6

我是Ruby的Nuby。我正在尋找一種方法來獲取當前執行行的方法的包含Class對象。這可能沒有硬編碼的類名?Ruby:是否可以確定我的Ruby方法正在執行的類而不對類名進行硬編碼?

# hardcoded example 
class A 
    def to_s 
    "I am a " + A.to_s # Class "A" is hardcoded here. Is there another way to reference the class A? 
    end 
end 

我想,也許self.class會的工作,但它並沒有給我什麼,我一直在尋找類時子類的。

# Following Outputs=> I am a Camel I am a Camel I am a Camel 
# but I want  => I am a Camel I am a Mammal I am a Animal 

class Animal 
    def to_s 
    "I am a " + self.class.to_s 
    end 
end 

class Mammal < Animal 
    def to_s 
    "I am a " + self.class.to_s + " " + super 
    end 
end 

class Camel < Mammal 
    def to_s 
    "I am a " + self.class.to_s + " " + super 
    end 
end 

puts Camel.new() 

那麼,有沒有一個關鍵字,方法或什麼,允許訪問包含類?

回答

3

試試這個

Class.nesting.first 

這給你定義類的方法。

class A 
    def example 
    { defining_class: Class.nesting.first, self_class: self.class } 
    end 
end 

class B < A 
end 

B.new.example 
# => {:defining_class=>A, :self_class=>B} 
+0

真的很好,我沒有想到!請注意,您需要'Class.nesting.first.name'作爲OP提出的語法。另外,OP在評論中寫道他不想要Modules,所以可能需要一些邏輯。無論如何,這些都是次要的挑戰:恭喜! –

+0

嵌套是詞法上下文,所以它將永遠是類中定義的方法的類。 (在一個不相關的說明中,我認爲OP從不透露他們的性別,所以最好用「他們」的代名詞。) – akuhn

+0

該方法也可以來自前置模塊,對吧?我從未使用過「他們」。我將在下次使用OP用戶名。 –

5

你需要Class#ancestors

Camel.ancestors 
#=> [Camel, Mammal, Animal, Object, Kernel, BasicObject] 

你會得到更多的類比你定義的,所以你需要停止在Object

class Animal 
    def to_s 
    "I am a " + self.class.ancestors.take_while{|klass| klass != Object}.join(' and a ') 
    end 
end 

class Mammal < Animal 
end 

class Camel < Mammal 
end 

puts Animal.new 
# => I am a Animal 
puts Mammal.new 
# => I am a Mammal and a Animal 
puts Camel.new 
# => I am a Camel and a Mammal and a Animal 

ancestors可以模塊或類,所以如果你只是想要課程,你可以使用:

def to_s 
    "I am a " + self.class.ancestors.take_while{|klass| klass < Object}.join(' and a ') 
end 

那麼,有沒有一個關鍵字,方法或什麼,允許訪問 包含類?

我找不到一個。添加

puts method(__method__).owner 

Animal#to_sMammal#to_s仍然返回Camel

+0

感謝您的代碼。這對我來說很有幫助,因爲我只是第二天進入Ruby。不過,我認爲你只是改進了我用來演示「self.class」的示例代碼,而不是我正在尋找的代碼。另外,我認爲你的代碼將包括模塊,如果有的話。例如「我是一個駱駝和一個SomeModule ...」,並且這將是不準確的,因爲模塊是「有」/構圖關係,而不是「是」。對?但所有這一切都不在話下。我正在尋找的答案應該讓我找到一個單獨的Class對象,並且它應該替換所有示例類中的「self.class」。 – successhawk

+0

我現在明白你的問題,但沒有找到任何東西。順便說一句,你的問題不是'.class',而是'self'。即使在爲「Animal」定義的方法中,它也保持與Camel對象相同。 –

+0

有,'Class.nesting.first' – akuhn

相關問題