Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Ruby automatically adding carriage returns

I am having problems constructing text files from a Windows machine to be read on a Linux environment.

def test

    my_file = Tempfile.new('filetemp.txt')

    my_file.print "This is on the first line"
    my_file.print "\x0A"
    my_file.print "This is on the second line"

    my_file.close

    FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")

end

0Ais the ASCII code for line feed, yet when I open the resulting file in Notepad++, I see it has appended CR and LF on the end of the line.

How do I add only a Line Feed as the new line character?

like image 714
kaybee99 Avatar asked Apr 16 '26 06:04

kaybee99


1 Answers

try setting the output separator $\ to \n.

def test
    $\ = "\n"
    my_file = Tempfile.new('filetemp.txt')

    my_file.print "This is on the first line"
    my_file.print "This is on the second line"

    my_file.close

    FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")

end

or you should be able to use #write which will not add the output separator

def test
    my_file = Tempfile.new('filetemp.txt')

    my_file.write "This is on the first line"
    my_file.write "\x0A"
    my_file.write "This is on the second line"

    my_file.close

    FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")

end
like image 189
Doon Avatar answered Apr 19 '26 01:04

Doon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!