开发者

Ruby on Rails Moving from CSV to FasterCSV

开发者 https://www.devze.com 2022-12-20 00:06 出处:网络
I currently have the following code to parse a csv file using the standard csv library @parsed_file=CSV::Reader.parse(params[:dump][:file])

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


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消