我有一个在 Windows 上运行的 Ruby 程序,它使用 Open3 调用一个 shell 命令(已知输出 UTF-16):
attrs={}
attrs[:stdout], attrs[:stderr], status = Open3.capture3(command)
unless attrs[:stderr].nil?
begin
attrs[:stderr].force_encoding(Encoding::UTF_16LE).encode!(Encoding::UTF_8)
rescue => e
attrs[:stderr] = attrs[:stderr].bytes.to_json.encode!(Encoding::UTF_8)
end
end
如果对 UTF_16LE 的 force_encoding 不起作用并引发异常,我只需保存字节,将其编码为 JSON 字符串并将其编码为 UTF_8。
好吧....抛出了异常,我在救援子句中捕获了输出字节数组。它看起来像这样:
[10,84,104,105,115,32,97,112,112,108,105,99,97,116,105,111,110,32,104,97,115,32,114,101,113,117,101,115,116,101,100,32,116,104,101,32,82,117,110,116,105,109,101,32,116,111,32,116,101,114,109,105,110,97,116,101,32,105,116,32,105,110,32,97,110,32,117,110,117,115,117,97,108,32,119,97,121,46,10,80,108,101,97,115,101,32,99,111,110,116,97,99,116,32,116,104,101,32,97,112,112,108,105,99,97,116,105,111,110,39,115,32,115,117,112,112,111,114,116,32,116,101,97,109,32,102,111,114,32,109,111,114,101,32,105,110,102,111,114,109,97,116,105,111,110,46,10]
如何将其转换回某种格式的文本。例如,如果我这样做:
irb> "dog".bytes
=> [100, 111, 103]
irb> "कुत्रा".bytes
=> [224, 164, 149, 224, 165, 129, 224, 164, 164, 224, 165, 141, 224, 164, 176, 224, 164, 190]
有没有办法以编程方式将 [100, 111, 103] 转换为“狗”或 [224, 164, 149, 224, 165, 129, 224, 164, 164, 224, 165, 141, 224, 164, 176, 224, 164, 190] 回到“कुत्रा”?有没有办法弄清楚我的输出字节数组是什么意思?
- - - - - - - - - - - - - 更新 - - - - - - - - - - - - ---
我挖了一点,但花了一段时间,因为“解码”不是一件事。但是,我对变量message中保存的数组执行了以下操作:
message.map{|c| c.chr}.join("")
=> "\nThis application has requested the Runtime to terminate it in an unusual way.\nPlease contact the application's support team for more information.\n"
所以我的问题解决了,因为错误消息不在 UTF-16LE 中。
但是,当我这样做时,我得到了以下结果:
irb> "कुत्रा".bytes.map{|c| c.chr}.join("")
=> "\xE0\xA4\x95\xE0\xA5\x81\xE0\xA4\xA4\xE0\xA5\x8D\xE0\xA4\xB0\xE0\xA4\xBE"
如何将这个看起来很奇怪的字符串或字节序列转换为更有意义的 "कुत्रा" ?