convert unicode into character with ruby

ⅰ亾dé卋堺 提交于 2019-12-03 07:35:59

问题


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

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


回答1:


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

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.




回答2:


Ruby 1.9 :

p "国".codepoints.first #=> 22269
p 22269.chr('UTF-8') #=> "国"


来源:https://stackoverflow.com/questions/4620549/convert-unicode-into-character-with-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!