我是Ruby的新手。考虑下面的代码,我在每个子类中重复if else语句。有没有办法将其分组为超类的初始化程序?谢谢你的帮助!
class TreeItem
def TreeItem.new(*args)
if self== TreeItem
raise "Attempt to create TreeItem"
else
super
end
end
def initialize(data)
@data=data
end
def raise_error(data)
raise "Attempt to create #{self.class} with #{data.class} object"
end
def toString()
raise "Abstract method toString() not implemented #{self}"
end
end
class IntItem <TreeItem
def initialize(data)
if data.kind_of? Integer
super(data)
else
raise_error(data)
end
end
end
class StringItem < TreeItem
def initilize(data)
if data.kind_of? String
super(data)
else
raise_error(data)
end
end
答案 0 :(得分:0)
您可以为此编写抽象方法(我将其命名为data_class
):
class TreeItem
def initialize(data)
if data.kind_of? data_class
@data = data
else
raise_error(data)
end
end
# ...
end
class IntItem <TreeItem
def data_class; Integer end
end
class StringItem < TreeItem
def data_class; String end
end
使用此实现,如果您将尝试创建TreeItem实例,则会出现method undefined
错误(您还可以在data_class
中实现自定义TreeItem
以引发更具体的异常。)< / p>