File.write bug

Hello all,

I’m relatively new to ruby and I think I’ve found a bug. It doesn’t
seem to be in my code.

I written this test script:

test.rb

File.open(“blaat.txt”,“w”) do |f|
f.write “test\r\n”
f.write “test\r”
f.write “test\n”
end
############################

And it produces unexpected results. It seems to insert a “\r” before
every “\n”. I have included the result of this script on my computer.

I’m running Windows XP SP2 and ruby 1.8.5.

Does anyone know what the problem could be and how to fix it?

Wouter S.

On Feb 7, 5:48 am, “Wouter S.” [email protected] wrote:

f.write “test\r”

Wouter S.

[blaat.txt]test
test test

It’s not a bug.

On Windows, “\n” evaluates to a carriage return and a line feed, what
you may be used to calling “\r\n”. If you open blaat.txt in SciTE (or
any similar text editor) and view the ends of lines (View -> End of
Line), you’ll see.

So what’s happening is that f.write “test\r\n” is writing a carriage
return, then “\n” which is a carriage return and a line feed.

On 2/7/07, Chris S. [email protected] wrote:

f.write “test\r\n”
Does anyone know what the problem could be and how to fix it?
any similar text editor) and view the ends of lines (View -> End of
Line), you’ll see.

So what’s happening is that f.write “test\r\n” is writing a carriage
return, then “\n” which is a carriage return and a line feed.

…and if you don’t like the behaviour, use File.open(‘xxxx’, ‘wb’) -
notice the ‘b’.
Or specify mode as IO::WRONLY | IO::BINARY

The same works for Python as well.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs