我看了其他ruby /编码相关的帖子,但一直未能弄清楚为什么以下不起作用。可能只是因为我很密集,但这是情况。Ruby字符串编码问题
在windows上使用Ruby 1.9。我有一组CSV文件,需要将一些数据附加到每行的末尾。每当我运行我的脚本时,附加的字符都是乱码。输入文本似乎是IBM437编码,而我追加的字符串以US-ASCII开头。我试过的关于在输入字符串或附加字符串上强制编码的东西似乎改变了结果输出。我很难过。目前的编码版本只是我试过的最后一个版本。
def append_salesperson(txt, salesperson)
if txt.length > 2
return txt.chomp.force_encoding('US-ASCII') + %(, "", "", "#{salesperson}")
end
end
salespeople = Hash[
"fname", "Record Manager"]
outfile = File.open("ActData.csv", "w:US-ASCII")
salespeople.each do | filename, recordManager |
infile = File.open("#{filename}.txt")
infile.each do |line|
outfile.puts append_salesperson(line, recordManager)
end
infile.close
end
outfile.close
您是否在脚本中使用编码魔术注释? – kch 2010-03-05 18:07:10