5

I have a requirement wherein I want to dynamically create a unicode string using interpolation.For e.g. please see the following code tried out 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}"

The hex-code 0x0905 corresponds to unicode for independent vowel for DEVANAGARI LETTER A.

I am unable to figure how to achieve the desired result.

2
  • 3
    It seems you don't know how to format code block, which is a little surprising to see on a long-time user, please read the help and don't add your signature any more. Commented Nov 25, 2014 at 10:29
  • Thanks Yu Hao.Will take care of your points in future. Commented Nov 25, 2014 at 10:47

2 Answers 2

5

You can pass an encoding to Integer#chr:

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

The parameter can be omitted, if Encoding::default_internal is set to UTF-8:

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

You can also append codepoints to other strings:

'' << hex #=> "अ"
Sign up to request clarification or add additional context in comments.

1 Comment

This answer seems more compact compared to Uri Agassi's answer. However both the techniques work smoothly. Thank you Uri and Stefan to both of you.
1

String interpolation happens after ruby decodes the escapes, so what you are trying to do is interpreted by ruby like an incomplete escape.

To create a unicode character from a number, you need to pack it:

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.