用<<连接字符串正在添加意想不到的新行

时间:2014-01-08 22:09:35

标签: ruby

作为数据清理工作的一部分,我需要在每行数据的末尾追加一个字符串。

export = File.new('C:\clean_file.txt' , 'w+')

File.open('C:\dirty_file.txt').each_with_index do |line, index|
    start_string = line.to_s

    # start_string => "23-SEP-13","201309","208164","F5140"
    # some gsub code on start_string...
    # start_string => "09/23/2013","201309","208164","Customer1"

    decoded_string = start_string
    decoded_string << %q(,"Accounts")
    export.puts decoded_string
end

但是,当我尝试使用&lt;&lt;附加字符串时操作员,我得到一个额外的回车:

# clean_file.txt looks like this =>
line1: "09/23/2013","201309","208164","Customer1"
line2: ,"Accounts"
line3: "09/24/2013","201309","208165","Customer2"
line4: ,"Accounts"
# etc.

我试过了:

decoded_string = start_string + %q("Accounts")

但得到了相同的结果,似乎&lt;&lt;是在Ruby中连接字符串的首选方法。我应该如何附加字符串以确保'clean_file.txt'如下所示?

# clean_file.txt SHOULD love look like this =>
line1: "09/23/2013","201309","208164","Customer1","Accounts"
line2: "09/24/2013","201309","208165","Customer2","Accounts"
# etc.

1 个答案:

答案 0 :(得分:3)

更改

start_string = line.to_s

start_string = line.chomp

换行符来自从文件中读取的行。