ruby - How to dump a 2D array directly into a CSV file? -
i have 2d array:
arr = [[1,2],[3,4]] i do:
csv.open(file) |csv| arr.each |row| csv << row end end is there easier or direct way of doing other adding row row?
assuming array numbers (no strings potentially have commas in them) then:
file.open(file,'w'){ |f| f << arr.map{ |row| row.join(',') }.join('\n') } one enormous string blatted disk, no involving csv library.
alternatively, using csv library correctly escape each row:
require 'csv' # #to_csv automatically appends '\n', don't need in #join file.open(file,'w'){ |f| f << arr.map(&:to_csv).join } if have , code bothers you, monkeypatch in:
class csv def self.dump_array(array,path,mode="rb",opts={}) open(path,mode,opts){ |csv| array.each{ |row| csv << row } } end end csv.dump_array(arr,file)
Comments
Post a Comment