Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: unicode character decimal value to \uXXXX conversion? .ord method not working

I'm trying to work with unicode characters, and the information provided by the string's .ord method doesn't help me. I'm used to working with codes like "\uXXXX".

ruby-1.9.3-p0 :119 > form[0]
=> "כ" 

ruby-1.9.3-p0 :120 > form[0].ord
=> 1499 
ruby-1.9.3-p0 :121 > puts "\u1499"
ᒙ

...

:-(

The values yielded by .ord seem to correspond to the 'decimal points' referred to here: http://www.i18nguy.com/unicode/hebrew.html

I don't know how to work with these values. How do I get the \uXXXX code from that character?

Thank you

like image 390
Walrus the Cat Avatar asked May 07 '12 03:05

Walrus the Cat


2 Answers

The \u syntax uses hexadecimal, you're giving it a decimal value. You want:

>> "%4.4x" % form[o].ord
"05db"
>> puts "\u05db"
כ
like image 59
mu is too short Avatar answered Nov 09 '22 08:11

mu is too short


mu is too short's answer is cool.

But, the simplest answer is:

'好'.ord.to_s(16)     # => '597d'
like image 8
zw963 Avatar answered Nov 09 '22 09:11

zw963