gpt4 book ai didi

ruby - 用 << 连接字符串会添加意外的新行

转载 作者:太空宇宙 更新时间:2023-11-03 18:19:27 24 4
gpt4 key购买 nike

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

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

但是,当我尝试使用 << 运算符附加字符串时,我得到了一个额外的回车符:

# 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")

但得到了相同的结果,并且 << 似乎是在 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.

最佳答案

改变

start_string = line.to_s

start_string = line.chomp

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

关于ruby - 用 << 连接字符串会添加意外的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21007646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com