2011-10-24 2 views
3

루비에서 둘러싼 모듈에 대한 참조를 어떻게 얻습니까?루비에있는 둘러싼 모듈에 대한 참조 얻기

module Foo 
    @@variable=1 

    def variable 
     @@variable 
    end 

    class A 
     def somemethod 
     puts "variable=#{Foo.variable}" #<--this won't run, resolving Foo 
             # as the class instead of the module 
     end 
    end 

    class Foo 
     ... # doesn't matter what's here 
    end 
end 

나는 혼란을 일으키는이 질문에 답했습니다. 이름을 고칠 정도로 쉽지만 루비에서 "올바른"방법이 무엇인지 궁금합니다. 이걸 실행하려고하면 Foo.variable을 Foo :: Foo.variable로 해결하려고 시도하는 것 같습니다. 물론 이는 실패 외부 모듈 방법을 참조 할 수있는 언어로 간단한 방법이 있어야한다 것 같다

답변

3
당신은 :: 접두사 Foo에 추가하여 외부 모듈 참조를 얻을 수 있습니다

:..

::Foo.variable 

예제 코드에서 :

module Foo 
    @@variable=1 

    def variable 
     @@variable 
    end 

    class A 
     def somemethod 
     puts "variable=#{::Foo.variable}" 
     end 
    end 

    class Foo 
     ... # doesn't matter what's here 
    end 
end 
+0

감사합니다. . 날 미쳤어. 내가하려고하면 –

+0

내가 얻을 : ' foo.rb : 14 :'것으로 someMethod에서 '정의되지 않은 메서드'변수'푸에 : 31 : foo.rb에서 모듈 (NoMethodError) 시도 ' –

+0

'

'에 메소드 변수를 다음과 같이 선언한다 :'def self.variable' – oesgalha

관련 문제