我是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()
那麼,有沒有一個關鍵字,方法或什麼,允許訪問包含類?
真的很好,我沒有想到!請注意,您需要'Class.nesting.first.name'作爲OP提出的語法。另外,OP在評論中寫道他不想要Modules,所以可能需要一些邏輯。無論如何,這些都是次要的挑戰:恭喜! –
嵌套是詞法上下文,所以它將永遠是類中定義的方法的類。 (在一個不相關的說明中,我認爲OP從不透露他們的性別,所以最好用「他們」的代名詞。) – akuhn
該方法也可以來自前置模塊,對吧?我從未使用過「他們」。我將在下次使用OP用戶名。 –