假设我们需要为树(或其他问题解决中所需的对象)定义一个通用类。由于我们的类结构可能非常复杂,因此我更喜欢在定义后定义类方法。 我们的通用类和其中的一个特定类是:
class BaseTree
class BaseNode; end
class NodeA < BaseNode; end
end
class Container
class Tree < BaseTree; end
end
在定义类结构之后,我们为所有节点设置#initialize
。
class BaseTree::BaseNode
def initialize x
p x
end
end
如果我们进行测试,那么一切都很好。
Container::Tree::NodeA.new(1)
# => 1
然而,如果我们按照以下方式添加一个方法:
class Container::Tree::NodeA
def some_method; end
end
然后它会打破 NodeA
和 BaseNode
之间的继承关系!!
Container::Tree::NodeA.new(2)
# ~> -:30:in `initialize': wrong number of arguments(1 for 0) (ArgumentError)
为了解决这个问题,我们必须明确地定义它。
class Container
class Tree < BaseTree
class NodeA < BaseNode; end # explicit inheritance
end
end
class Container::Tree::NodeA
def some_method; end
end
或者通过以下方式
class Container::Tree::NodeA < Container::Tree::BaseNode
def some_method; end
end
class Container::Tree::NodeA < BaseTree::BaseNode
def some_method; end
end
最后一种方法只需要使用一次——在我们添加一个方法的第一次,之后的定义中就可以跳过父类。
class Container::Tree::NodeA
def another_method; end
end
之后它可以正常工作,但我觉得这样做很繁琐,特别是如果有很多树种和许多不同的节点。
是否有更优雅的方法来定义它们?