2013-06-05 96 views
0

我有一些類實例,需要從它們獲取常量。作爲例子:類實例ruby的常量

class MyClass 
    CONST = 1 
end 

my_class = MyClass.new 
my_class.CONST => undefined method `CONST' for #<MyClass:0x0000000234ca68> 
my_class::CONST => #<MyClass:0x00000002ba75a0> is not a class/module 

我知道,像這樣的例子將正常工作:

my_class.class::CONST 
MyClass::CONST 

紅寶石是否有正從類實例常量一些簡單的方法?

+0

爲什麼你不能從類本身獲得常量? –

+2

'my_class.class :: CONST'有什麼問題?你期待什麼比這更簡單嗎? – sawa

+0

我有方法回到我的某個類的實例。除了常量之外,我需要他們的方法。所以'.class'不適合我。 – facetostool

回答

0

我將課程改爲模塊。並且該方法不會返回類的實例和模塊的名稱!當然,如果你有機會使用靜態方法,這在我的例子中我買不起。如何在沒有模塊的情況下做到這一點,我不知道。