On Feb 2, 9:53 pm, Michael Sc [email protected] wrote:
[āmalignā, 1.732],
would I write this to its own csv file?
require ācsvā
outfile = File.open(ānewfile.csvā, āwbā)
x=CSV.open(āoldfile.csvā, ārā)
x.sort_by{|a| a.values_at( 2,0,1 ) }.each{|a| outfile.print a }
outfile.close
I tried outfile.p(doesnāt work), outfile.print(takes out the commas) and
outfile.put(takes out the breaks). I know this should be incredibly
easy but I am clearly missing something.
Before writing each record (i.e., each array of fields) to the file,
it must first be converted to a proper csv string.
The ācsvā package has a method for doing this, I presume.
If you donāt wanāt to use that, try this:
class Array
def to_csv
s = āā
map { |item|
str = item.to_s
# Quote the string if it contains the field-separator or
# a " or a newline or a carriage-return, or if it has leading or
# trailing whitespace.
if str.index( ā,ā ) or /^\s|["\r\n]|\s$/.match(str)
str = ā"ā + str.gsub( /"/, ā""ā ) + ā"ā
end
str
}.join( ā,ā )
end
end
puts [ 674, āyesā, āJones,Tomā, āfoo"barā, " space " ].to_csv
ā output -----
674,yes,āJones,Tomā,āfooāābarā," space "