如何停止Ruby自动添加回车

时间:2015-05-12 15:43:50

标签: ruby linux windows

我在从Windows机器上构建文本文件时遇到问题,无法在Linux环境中读取。

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

0A是换行符的ASCII码,但是当我在Notepad ++中打开生成的文件时,我发现它在行尾有附加CR LF。

如何将换行符添加为换行符?

2 个答案:

答案 0 :(得分:3)

尝试将输出分隔符$\设置为\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

或者您应该能够使用不会添加输​​出分隔符的#write

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

答案 1 :(得分:1)

以二进制模式打开文件会导致Ruby''抑制EOL< - > Windows上的CRLF转换'(请参阅here)。

问题在于Tempfiles are automatically opened in w+ mode。在创建Tempfile时我找不到改变它的方法。

答案是使用binmode创建后更改它:

def test


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

    my_file.print "This is on the first line"
    my_file.print "\x0A"    # \n now also works as a newline character
    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