2014-05-13 28 views
0

我是新來的面向對象編程/建模,我一直使用Ruby來編程一些平面圖算法。我所試圖做的是這樣的:是否允許並安全地在Ruby中重新使用類新方法(初始化)?

class Twin 

    def initialize(name1,name2) 
    ## creates two twin brothers and "returns" one of them 
    end 

    def name 
    @name 
    end 

    def brother 
    @brother 
    end 

end 

我發現沒有辦法在一杆,以創建初始化雙胞胎除非經常性,因爲它遵循:

def initialize(name1,name2) 
    if @@flag.nil? 
     @@flag = self 
     @mybrother = Twin.new(name1,name2) 
     @name = name1 
    else 
     @mybrother = @@flag 
     @@flag = nil 
     @name = name2 
    end 
    end 

我可以在在初始化方法中使用遞歸?我實現了這個方法,它似乎工作。但我不確定它是否依賴於解釋器版本。

我知道我可以寫一個班級Person和第二班Twin來創建併成對加入。但對我來說這似乎是一個人造的模型。我試圖模仿我在幾年前使用記錄在C中編寫的數據結構。


編輯:挖了很多,基於@iamnotmaynard的建議後,我重寫我的代碼如下方式:

class Twin 

    def self.generate_twins(name1,name2) 
    t1 = Twin.allocate 
    t2 = Twin.allocate 
    t1.instance_variable_set(:@name, name1) 
    t1.instance_variable_set(:@brother, t2) 
    t2.instance_variable_set(:@name, name2) 
    t2.instance_variable_set(:@brother, t1) 
    t1 
    end 

    def initialize 
    raise "Use generate_twins to create twins" 
    end 

    def name 
    @name 
    end 

    def brother 
    @brother 
    end 

end 

這段代碼表達什麼,我沒有初始化的遞歸尋找。謝謝大家的回覆和評論,幫助我找到答案。

+1

而非'initialize'做,創建一個類的方法(像'generate_twins'),其可以創建Twin'的'的兩個實例,並返回一個(或兩個)。 – iamnotmaynard

+0

這似乎是一個更好的解決方案。我會嘗試。 – Roverflow

回答

0

您應該創建一個新的類方法來創建兩個雙胞胎。我不會像那樣使用初始化器。

0

我建議爲此分開上課。

我不知道什麼是twins組成的,但你可以創建一個類Single,將舉行有關單一的方法,然後另一個類「雙」,你會以兩種Single的傳球到。

Class Single 
    def initialize(..) 
     #Initialize the single object here 
    end 
    #include any methods relevant to the single object 
end 

Class Twin 
    def initialize(single1, single2) 
     #store the singles in the class 
    end 
    #Put methods that use both singles here 
end 
相關問題