我是一个新手程序员,在过去的几周里一直在自学Ruby我遇到了一个程序(CSV导入器/JSON导出器)的问题,希望有人能帮助我。

def convert_csv_to_json(csv_file_name)
    CSV.foreach(csv_file_name) do |row|
      JSON.pretty_generate(row)
    end
    test = FileExportManager.new
    test.export_json_to_computer(csv_file_in_json)
  end

我希望export_json_to_computer方法将foreach循环的结果导出为参数我没能做到这一点有人能提些建议吗谢谢。
编辑-包含已编辑的版本FileExportManager类
class FileExportManager

  def export_json_to_computer(file)
    write_to_file(file)
  end

  def assign_file_name
# this method names file and assigns .json extension
    File.new(file_name, 'w')
  end

  def write_to_file(file)
    File.open(file_name, 'w') do |row|
      row.puts file
    end
  end
end

最佳答案

根据当前代码的结构,您希望将csv文件读取到内存中,然后将其转换为json并将字符串传递到export_json_to_computer文件,如下所示:

def convert_csv_to_json(csv_file_name)
  rows = JSON.pretty_generate(CSV.read(csv_file_name).to_a)
  test = FileExportManager.new
  test.export_json_to_computer(rows)
end

关于ruby - Ruby for Each循环将结果传递到方法参数中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31763554/

10-14 19:44
查看更多