让我们考虑一下:
class Container
def function_one
...
end
def function_two
...
end
def function_three
...
end
attr_accessor :result_from_function_one
attr_accessor :result_from_function_two
attr_accessor :result_from_function_three
end
由于我无法为其他类创建单独的算法体,因此我创建了四个单独的类。当我需要运行算法1时,我创建了一个带有函数1的类,依此类推:
class Container
...
end
class ContainerWithFunctionOne < Container
def function_one
...
end
attr_accessor :result_from_function_one
end
class ContainerWithFunctionTwo < Container
def function_two
...
end
attr_accessor :result_from_function_two
end
class ContainerWithFunctionThree < Container
def function_three
...
end
attr_accessor :result_from_function_three
end
但是当我将function_one
与function_two
结合使用时,我遇到了一个问题,因为他们需要使用相同的数据结构。所以我在考虑将班级Container
划分为模块:
module FunctionOne
class Container
def function_one
...
end
attr_accessor :result_from_function_one
end
end
module FunctionTwo
class Container
def function_two
...
end
attr_accessor :result_from_function_two
end
end
module FunctionThree
class Container
def function_three
...
end
attr_accessor :result_from_function_three
end
end
但是当我尝试运行它时:
require_relative 'FunctionOne'
require_relative 'FunctionTwo'
require_relative 'FunctionThree'
containter = Container.new
container.function_one
container.function_two
container.function_three
它给出了运行时错误:
in `<top (required)>': uninitialized constant Container (NameError)
我不知道如何解决这个问题。
答案 0 :(得分:2)
你可以尝试
container = FunctionOne::Container.new
创建一个新容器