"\351\276\205" irb(main):005:0> -6ren">
gpt4 book ai didi

ruby - 在ruby中将utf-8转换为unicode

转载 作者:数据小太阳 更新时间:2023-10-29 07:43:34 25 4
gpt4 key购买 nike

“龅”的UTF-8为E9BE85,unicode为U+9F85。以下代码未按预期工作:

irb(main):004:0> "龅"
=> "\351\276\205"
irb(main):005:0> Iconv.iconv("unicode","utf-8","龅").to_s
=> "\377\376\205\237"

P.S: 我使用的是 Ruby1.8.7。

最佳答案

Ruby 1.9+ 比 1.8.7 更适合处理 Unicode,因此,我强烈建议尽可能在 1.9.2 下运行。

部分问题是 1.8 不理解 UTF-8 或 Unicode 字符的长度可以超过一个字节。 1.9 确实理解这一点,并引入了诸如 String#each_char 之类的东西。

require 'iconv'

# encoding: UTF-8

RUBY_VERSION # => "1.9.2"
"龅".encoding # => #<Encoding:UTF-8>
"龅".each_char.entries # => ["龅"]
Iconv.iconv("unicode","utf-8","龅").to_s # =>

# ~> -:8:in `iconv': invalid encoding ("unicode", "utf-8") (Iconv::InvalidEncoding)
# ~> from -:8:in `<main>'

要使用 Iconv 获取可用编码列表,请执行以下操作:

require 'iconv'
puts Iconv.list

列表很长,所以我不会在这里添加。

关于ruby - 在ruby中将utf-8转换为unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4965796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com