Ruby 2:从二进制ASCII-8BIT数据检测编码

Ruby 2: Detect encoding from binary ASCII-8BIT data

我必须从外部来源加载一些数据。当我查看编码时,Ruby 告诉我 ASCII-8BIT,二进制文件。但是,一些来源编码为 ISO-8859-1,其中一些在 UTF-8 中。当我尝试将 ISO-8859-1 编码的内容转换为 UTF-8 时,出现错误。但是当我做类似 content.force_encoding('ISO-8859-1').encode('UTF-8') 的事情时,一切正常。

但是,反过来就不行了。当我尝试将 UTF-8 数据编码为 ISO 时,它以损坏的字符结束,例如 .

So, is there a way to detect the "underlying" encoding of the ASCII-8BIT data, and then convert it to UTF-8?

我快速 google 找到了布莱恩·洛佩兹 (Brian Lopez) 笔下的查洛克·福尔摩斯 gem。看起来它执行了您要执行的检测过程。

https://github.com/brianmario/charlock_holmes