2013-01-06 144 views
-1

我知道全局變量不應該被使用,但現在它是唯一能夠工作的東西。所以我正在尋找替代品。我想要做的是通過@array,這是方法two在類New,方法one。我能夠完成這個的唯一方法是使用$arrayRuby全局變量替代

module Test::Abc 
    class << self 
    def one 
     .... 
    end 

    class New 
     def two 
     @array=[] 
     end 
    end 
    end 
end 

這裏就是我做得到,我需要的結果......

module Test::Abc 
    class << self 
    def one(array) 
     .... 
    end 
    end 

    class New 
    def two 
     @array=[] 
     [email protected] 
     Test::Abc::one(array) 
    end 
    end 
end 
+0

An ins tance變量'@ array'特定於'Test :: Abc :: New'的特定實例。除非您在'one'中指定您正在查看的'Test :: Abc :: New'的哪個實例,否則您將無法訪問它。 – sawa

+0

謝謝sawa的回覆......你已經描述了我無法做到的事情! :)我不知道如何從一個@array指定。 – JoMojo

+0

如果你能完成某件事的唯一方法是使用全局變量,你應該非常強烈地考慮重新設計你的代碼。例如,爲什麼不使用方法參數?此外,你是否確定要在'Test :: Abc'的單例中定義'New'類? –

回答

1

這就是我想出了一個解決方案...

module Test::Abc 
    class << self 
    def one(array) 
     .... 
    end 
    end 

    class New 
    def two 
     @array=[] 
     [email protected] 
     Test::Abc::one(array) 
    end 
    end 
end 
0

隨着你的答案,這也應該工作(輕微修改):

module Test::Abc 
    class << self 
    def one(array) 
     .... 
    end 
    end 

    class New 
    def two 
     @array=[] 
     Test::Abc::one(@array) 
    end 
    end 
end