Ruby tries to dynamically create unicode strings, throwing the error "invalid Unicode escape"

I have a requirement in which I want to dynamically create a Unicode string using interpolation. see the following code verified in irb

2.1.2 :016 > hex = 0x0905
 => 2309 
2.1.2 :017 > b = "\u#{hex}"
SyntaxError: (irb):17: invalid Unicode escape
b = "\u#{hex}"

Hex code 0x0905 corresponds to unicode for an independent vowel for DEVANAGARI LETTER A.

I can’t understand how to achieve the desired result.

+4
source share
2 answers

You can pass the encoding Integer#chr:

hex = 0x0905
hex.chr('UTF-8') #=> "अ"

The parameter can be omitted if Encoding::default_internalset to UTF-8:

$ ruby -E UTF-8:UTF-8 -e "p 0x0905.chr"
"अ"

You can also add code pages to other lines:

'' << hex #=> "अ"
+2
source

, ruby ​​ escape-, , , .

, pack:

hex = 0x0905
[hex].pack("U")
=> "अ"
+1

All Articles