我看了其他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