Chris Kong
Chris Kong

Reputation: 399

Ruby CSV << [] does not line break properly

I have a wired issue here,

I use standard CSV << ["a", "b"] in my code, and the output file behaves just fine in Excel and Sublime Text 2(elegantly line break)

However I open the file with Windows notepad, it turns out to be a single line.

And I try to use VBA to read this file line by line, only to get one single line.

Here is my code,

require "csv"
CSV::open("some_file.csv", "w") do |csv|
  csv << ["a", "b"]
  csv << ["a1", "b1"]
end

In Sublime Text 2 I get

a,b
a1,b1

However in Windows notepad, I only get

a,ba1, b1

Any idea why?

[update] It was Windows notepad, not Windows Text Editor, sorry for the mistake.

Upvotes: 0

Views: 802

Answers (1)

mdemolin
mdemolin

Reputation: 2534

The reason is that unix and windows systems do not handle newline representation the same way. See this wikipedia article. To simplify, unix uses LF, which is written as \n whereas windows expects CR+LF: \r\n. This is why it appears to be on the same line when opening in windows. You can use @arup-rakshit solution, extra \r should not hurt, but you may need to specify it when reading it again. Otherwise, there are some various tools to convert a unix file to a windows file and vice versa.

Upvotes: 2

Related Questions