0
我有YAML文件test.yml
可以在UTF-8或ANSI編碼:
:excel:
"Test":
"eins_Ä": :eins
"zwei_ä": :zwei
當我加載文件因此,我需要它在UTF-8編碼試圖把所有的字符串:
require 'yaml'
file = YAML::load_file('C:/Users/S61256/Desktop/test.yml')
require 'iconv'
CONV = Iconv.new("UTF-8", "ASCII")
class Test
def convert(hash)
hash.each{ |key, value|
convert(value) if value.is_a? Hash
CONV.iconv(value) if value.is_a? String
CONV.iconv(key) if key.is_a? String
}
end
end
t = Test.new
converted = t.convert(file)
p file
p converted
但是當我嘗試運行此示例腳本,它打印:
個in 'iconv': eins_- (Iconv:IllegalSequence)
問題:
爲什麼錯誤出現了,我該怎麼解決呢?
2.是否有另一種更合適的方式來獲取UTF-8文件的內容?
注: 我需要此代碼與Ruby 1.8以及Ruby 2.2兼容。對於Ruby 2.2,我會用String :: encode替換所有Iconv的東西,但這是另一個話題。