2011-07-26 33 views
9

我有一個模塊在一個類變量它訪問模塊的類變量在類中使用Ruby

module Abc 
    @@variable = "huhu" 

    def self.get_variable 
    @@variable 
    end 

    class Hello 
    def hola 
     puts Abc.get_variable 
    end 
    end 
end 

a = Abc::Hello.new 
a.hola 

是否有可能得到@@variableHello不使用get_variable方法?我的意思是像Abc.variable會很好。只是好奇。

+0

的[哪有Ruby的attr_accessor農產品類變量或類的實例變量而不是實例變量?](http://stackoverflow.com/questions/895747/how-can-可能重複ruby-attr -accessor -products-class-variables-or-class-instance-variables) –

回答

4

您不能在模塊Abc中的Hello類的範圍內直接訪問@@variable(即Abc.variable)。爲什麼?因爲,當Ruby解釋器看到類似Abc.variable的東西時,它會認爲variable是Abc的類/模塊方法。

在Ruby中進行編程時,認爲Ruby方式非常重要。

+0

備註:如果你想在很大程度上克服這些想法,我已經在最近舉辦的Ruby Conf India 2011中分享了我的經驗。請隨時在http://kartzontech.blogspot.com/2011/06/ruby-conf-india-2011.html觀看我的演講,並提供您的評分和反饋。最重要的是,閱讀最後一張幻燈片,我提到的資源有助於塑造我對Ruby方式的思考。 – karthiks

-1

試試這個

Abc.class_variable_get(:variable) 
+0

請擴大您的代碼或補充說明,否則您有可能讓版主刪除您的答案。 – sshashank124