使用ruby将unicode转换为字符

the*_*gah 9 ruby unicode cjk

我在unicode中找到了一个汉字字典.我正在尝试从这个字典中构建一个Character数据库,但我不知道如何将unicode转换为一个字符..

p "?".unpack("U*").first #this gives the unicode 22269
Run Code Online (Sandbox Code Playgroud)

如何转换22269回与上面一行相反的字符值.

ste*_*lag 16

Ruby 1.9:

p "?".codepoints.first #=> 22269
p 22269.chr('UTF-8') #=> "?"
Run Code Online (Sandbox Code Playgroud)

  • 显示+1可以将编码传递给#chr. (3认同)

Phr*_*ogz 13

[22269].pack('U*') #=> "?" or "\345\233\275"
Run Code Online (Sandbox Code Playgroud)

编辑:适用于1.8.6+(在1.8.6,1.8.7和1.9.2中验证).在1.8.x中,您将获得一个表示单个Unicode字符的三字节字符串,但使用putson会导致正确的中文字符出现在终端中.

  • @Sam显然你使用的版本并不重要.(见编辑):) (3认同)