Michael Francis
Michael Francis

Reputation: 8747

Print String in form of unicode codes in Ruby

Is there some method I can call on "hello" to get '\u0068\u0065\u006c\u006c\u006f'?

Upvotes: 2

Views: 476

Answers (2)

Linuxios
Linuxios

Reputation: 35783

Yes and no. String#codepoints returns these in an array of integers:

"hello".codepoints #=> [104, 101, 108, 108, 111]

If you need it as escape sequences, try this:

"hello".codepoints.map {|c| "\\u#{sprintf("%04x", c)}"}.join

And if you want another solution (credit to @MattyK in comments):

"hello".codepoints.map{|c| '\u%04X' % c}.join

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122383

Like this?

"hello".unpack('U*').map{ |i| "\\u" + i.to_s(16).rjust(4, '0') }.join
=> "\\u0068\\u0065\\u006c\\u006c\\u006f"

Upvotes: 1

Related Questions