10

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

1

2 Answers 2

16

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

>> "%4.4x" % form[o].ord
"05db"
>> puts "\u05db"
כ
6
  • Thanks! What's the "%4.4x" % part doing? May 7, 2012 at 6:58
  • @WalrustheCat: ruby-doc.org/core-1.9.3/String.html#method-i-25, "%.4x" is sufficient though. May 7, 2012 at 7:05
  • 2
    I prefer the more self-explanatory form %04x for zero padding. May 7, 2012 at 14:17
  • 1
    How can I use "\u" syntax in script? So basically what I want is: code = "0028" character = "\u#{0028}" # => "(" Expected character = "\\u#{0028}" # => "(" Expected Both of the above does not work. Any suggestions? Aug 26, 2013 at 6:10
  • 3
    @Agent47DarkSoul: Array#pack is one way: ['05db'.to_i(16)].pack('U') is 'כ' for example. Aug 26, 2013 at 6:26
9

mu is too short's answer is cool.

But, the simplest answer is:

'好'.ord.to_s(16)     # => '597d'
1
  • You are right~. Thanks. althougth you can use 5db like this: puts "\u{5db}"
    – zw963
    Dec 11, 2014 at 1:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.