我是新來的面向對象編程/建模,我一直使用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
這段代碼表達什麼,我沒有初始化的遞歸尋找。謝謝大家的回覆和評論,幫助我找到答案。
而非'initialize'做,創建一個類的方法(像'generate_twins'),其可以創建Twin'的'的兩個實例,並返回一個(或兩個)。 – iamnotmaynard
這似乎是一個更好的解決方案。我會嘗試。 – Roverflow