《Ruby基礎教程》的第二十二章,有這樣一段示例代碼,意圖刪除讀取的HTML文件的頭部和尾部,並保存在新的TXT文件中。
1: htmlfile = "cathedral.html"
2: textfile = "cathedral.txt"
3:
4: html = File.read(htmlfile)
5:
6: File.open(textfile, "w") do |f|
7: in_header = true
8: html.each_line do |line|
9: if in_header && /<a name="1">/ !~ line
10: next
11: else
12: in_header = false
13: end
14: break if /<a name="version">/ =~ line
15: f.write line
16: end
17: end
但是我們試着將它執行一下卻發現,系統會報錯,並定位出許多錯誤點來。我們看一下錯誤信息“invalid byte sequence in GBK (ArgumentError)”,可以得知是文字編碼的問題。實際上是由於internal encoding 和 extertal encoding的不同造成的,我們只需在代碼前追加一行以下代碼就可以了。
Encoding.default_external = Encoding.find('utf-8')