我是面向对象编程/建模的新手,我一直在使用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
我发现没有办法在initialize中一次性创建两个双胞胎,除非像下面这样循环:
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
这段代码表达了我要找的东西,没有初始化的递归。谢谢你们的回答和评论,帮助我找到了它。
您应该创建一个新的类方法来创建两个双胞胎。我不会这样使用初始化式
我建议对此设置单独的类。
我不确定twins
是由什么组成的,但是你可以创建一个类Single
,它将保存与单个相关的方法,然后另一个类"Twin",你将在两个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