Ruby on Rails Moving from CSV to FasterCSV

拈花ヽ惹草 提交于 2019-12-08 11:56:19

问题


I currently have the following code to parse a csv file using the standard csv library

@parsed_file=CSV::Reader.parse(params[:dump][:file])
@parsed_file.each  do |row|
#some code
end

I want to move this to faster csv for the increased speed. Does anyone know the equivalent of the above for FasterCSV?

Thanks


回答1:


CSV::Reader.parse(File.open('file.csv')){|row| puts row} 
or
CSV::Reader.parse("some, content\nanother, content"){|row| puts row} 

and

FasterCSV.parse(File.open('file.csv')){|row| puts row}
or
FasterCSV.parse("some, content\nanother, content"){|row| puts row}

are equivalent.

But

FasterCSV.read('filename') 

takes filename as parameter and reads and parse data from the file however you are dumping the file content as you are passing data in the parameter

@parsed_file = FasterCSV.parse(params[:dump][:file])
@parsed_file.each do |row| 
  puts row
  # and do some operations
end

should work fine.




回答2:


To do it with a file path (as you appear to be):

FasterCSV.read(params[:dump][:file])

You can check the FasterCSV docs for other ways to do it (e.g., process each row as it's parsed, or read from a string instead of a file).



来源:https://stackoverflow.com/questions/2264294/ruby-on-rails-moving-from-csv-to-fastercsv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!