Rails: Files get filled with trailing whitespace

267 views Asked by At

The problem I have is that whenever I save some values to a File, Rails magically adds trailing whitespace to each line.

For example when I read the file the initaial content got manipulated:

"cv" => "cv\r\n"

"cv\r\nvd" => "cv\r\n\r\nvd\r\n"

Here is how I create my File:

File.open(path, "w+") do |f|
    f.truncate(0)
    f.puts value
end

I appreciate each help!

1

There are 1 answers

12
Eric Duminil On

Theory

If value doesn't have a trailing newline, value.chomp won't change anything because the newline doesn't come from value but from puts :

Writes a record separator (typically a newline) after any that do not already end with a newline sequence.

IO#write is the method you're looking for.

Finally, f.truncate(0) isn't needed because w+ stands for :

"w+" Read-write, truncates existing file to zero length or creates a new file for reading and writing.

Example

path = "test.txt"
value = 2

File.open(path, "w+") do |f|
    f.write value
end

p File.read(path)

returns :

"2"

With puts instead of write, it returns :

"2\n"

Newlines inside the string ?

If for some reason, value is a String with newlines inside, chomp and write won't help. Use gsub to replace multiple newlines with just one :

path = "test.txt"
value = "Hello\r\n\r\nWorld\n\nLine #3\r\rLine #4"

File.open(path, "w+") do |f|
    f.write value.gsub(/\R+/,"\n")
end

p File.read(path)
#=> "Hello\nWorld\nLine #3\nLine #4"

If you want spaces instead of newlines :

f.write value.gsub(/\R+/," ")