用Ruby将unicode转换为字符 [英] convert unicode into character with ruby

查看:313
本文介绍了用Ruby将unicode转换为字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个用unicode编写的汉字字典。我正在尝试从这本词典中建立一个字符数据库,但是我不知道如何将unicode转换为字符。.

I found a dictionary of Chinese characters in unicode. I'm trying to build a database of Characters out of this dictionary but I don't know how to convert unicode to a character..

p "国".unpack("U*").first #this gives the unicode 22269

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

How can convert 22269 back into the character value which would be the opposite of the line above.

推荐答案

[22269].pack('U*') #=> "国" or "\345\233\275"

修改:适用于1.8.6+(已在1.8.6、1.8.7和1.9.2中验证)。在1.8.x中,您得到了一个代表单个Unicode字符的三字节字符串,但是在其上使用 puts 会导致在终端中显示正确的中文字符。

Edit: Works in 1.8.6+ (verified in 1.8.6, 1.8.7, and 1.9.2). In 1.8.x you get a three-byte string representing the single Unicode character, but using puts on that causes the correct Chinese character to appear in the terminal.

这篇关于用Ruby将unicode转换为字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆