Ruby 请教下 Ruby 中如何将 UTF-8 编码的中文转为 Unicode 编码方式存在文件中

juhong · February 20, 2019 · Last by juhong replied at March 27, 2019 · 2808 hits

或者说如何用 io 将中文用 unicode 编码写入 txt!! 目前用的是 ruby2.0 版本

utf8 已经是 unicode 了 你要说在 win 记事本打开,搜 utf8 with bom,就是在文本开头加一字节特殊的标记用来指定大小端

unicode 是字符集

utf-8 和 utf-16 是 uncode 的具体编码方式

utf-8 中文用 3 个字节 (好像不全是),英文用 1 个字节

pry(main)> '我'.encoding
=> #<Encoding:UTF-8>
pry(main)> '我'.bytes
=> [230, 136, 145]
pry(main)> 'a'.bytes
=> [97]

utf-16 中文英文都是 2 个字节

pry(main)> '我'.encode("UTF-16BE").bytes
=> [98, 17]
pry(main)> 'a'.encode("UTF-16BE").bytes
=> [0, 97]

如果都是中文,utf-16 编码可以让文件相对小些,不过感觉现在流行用 utf-8

多谢,后来用的 utf-16

You need to Sign in before reply, if you don't have an account, please Sign up first.