清理传入字符串的标准方法?

时间:2012-10-26 16:51:21

标签: ruby character-encoding

我与几个外部服务集成,我通过http下载文件。我发现在我的系统中使用它们之前我必须转换/清理文件的名称。所以我在代码的不同部分都有这样的东西:

name = name.encode('UTF-8', 'ASCII-8BIT', invalid: :replace, undef: :replace, replace: '')
name = name.encode('UTF-8', 'ISO-8859-1', invalid: :replace, undef: :replace, replace: '')

在每种情况下,我都不得不问服务我应该期待什么编码。

这是解决此问题的唯一方法,还是有某种更标准和通用的方法来清理传入的字符串?

1 个答案:

答案 0 :(得分:0)

在Ruby 1.9.x中有一个外部和内部编码,它们都默认为全局编码。外部文件被认为是在配置的外部编码中,并自动转换为内部编码。您可以通过Encoding.default_externalEncoding.default_internal全局设置这些编码。您可以基于每个文件指定它们作为open方法的参数,如以下示例所示:

File.open('/path/to/some/file', 'r', external_encoding: 'US-ASCII', internal_encoding: 'UTF-8')

请注意,您也可以单独指定每个。

有关其他信息,请参阅this blog post