【发布时间】:2015-09-23 11:18:39
【问题描述】:
问题:
我有可以用 UTF-8 或 ANSI 编码的 yaml 文件 test.yml:
: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)
问题:
1.为什么会出现错误,我该如何解决?
2.是否有另一种(更合适的)方法来获取 UTF-8 格式的文件内容?
注意: 我需要此代码与 Ruby 1.8 和 Ruby 2.2 兼容。对于 Ruby 2.2,我会用 String::encode 替换所有 Iconv 的东西,但这是另一个话题。
【问题讨论】: