Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何避免在模块中使用实例变量?_Ruby_Module_Architecture_Instance Variables - Fatal编程技术网

Ruby 如何避免在模块中使用实例变量?

Ruby 如何避免在模块中使用实例变量?,ruby,module,architecture,instance-variables,Ruby,Module,Architecture,Instance Variables,我正在草拟CSV将如何验证模块的工作。有没有一种方法可以避免polute类包含带有实例变量的模块 该创意的灵感来源于以下内容: employee_csv_importer.rb(使用模块) csv_verify.rb module CsvVerify puts "included" def headers(*names) @config = Config.new end end config.rb module CsvVerify class Config en

我正在草拟CSV将如何验证模块的工作。有没有一种方法可以避免polute类包含带有实例变量的模块

该创意的灵感来源于以下内容:

employee_csv_importer.rb(使用模块)

csv_verify.rb

module CsvVerify
  puts "included"

  def headers(*names)
    @config = Config.new
  end
end
config.rb

module CsvVerify
  class Config

  end
end
那么,我如何重新组织它,以避免用@config污染EmployeeCsvImporter

附言。 为什么现在还不起作用呢?
为什么我要从运行employee_csv_importer.rb获得此输出

included
/data/gems/csv_verify/examples/1_employees.rb:6:in `<class:EmployeeCsvImporter>':
undefined method `headers' for EmployeeCsvImporter:Class (NoMethodError)
包括在内
/data/gems/csv\u verify/examples/1\u employees.rb:6:in`:
EmployeeCsvImporter:Class(NoMethodError)的未定义方法“headers”

我建议您在编写功能时不要先使用
模块
包含
。这有助于形成结构,特别是如果您是Ruby新手


通过include
CsvVerify
添加的方法被添加为实例方法,而不是类方法。因此,您有了这个
NoMethodError

def self.headers也不起作用。所以你建议我改为让CsvVerify类并让EmployeeCsvImporter继承它?此外,我对ruby并不陌生,但我对编写模块很在行。在其他语言中从未发现过类似的概念,总有一天必须掌握它。您需要使用提供
header
方法的模块扩展您的类。我建议您首先写出类的全部功能,然后决定如何以及是否需要将其拆分为模块。好的,谢谢,但这意味着@config将是一个类变量?是的。您正在
EmployeeCsvImporter
中从类级别配置头。如前所述:我首先在一个类中编写整个功能,以使某些功能正常工作。然后通过提取使其可重用。特别是如果你是新手。
included
/data/gems/csv_verify/examples/1_employees.rb:6:in `<class:EmployeeCsvImporter>':
undefined method `headers' for EmployeeCsvImporter:Class (NoMethodError)