Question

I have some database records in a Rails app that I'm trying to export to CSV, avoiding line breaks in the values. I run something to the effect of this:

File.open(new_file_path, 'w+') do |f|
  bio = c.biography.gsub("\n", "->")
  f.print "\"#{bio}\","
end

And I see results like this:

"Katcho Achadjian was first elected to the Assembly in 2010.
->
->Prior to being elected to the Legislature, Achadjian served as a member of the San Luis Obispo County Board of Supervisors from 1998 to 2010. 
->
->Achadjian graduated from Cal Poly San Luis Obispo with a bachelor’s degree in business administration. Achadjian and his wife have two adult children and reside in Arroyo Grande.",

You'll notice that the substituted character sequence appears with line breaks as well. Is there another encoding for line break that I'm somehow missing?

Was it helpful?

Solution

It depends on the platform.

On Windows you'll have \r\n (carriage return, new line). On Linux, OS X, and other Unix-like systems, it is just \n (new line). On Classic Mac OS (up to version 9) it is just \r (carriage return).

Probably you are using windows. The best way to deal with cross-platform texts is this:

  1. substitute \r\n with \r
  2. substitute \r with \n

This way you'll end up with just \n, whatever platform the text originated from and you'll have the benefit of uniforming line endings, because some editors do not touch unmodified lines and on saving you end up with mixed line endings, which are even worse than this.

OTHER TIPS

Try modifying your gsub to this:

gsub(/\r?\n/, "->")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top