Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fromCharCode equivalent in Ruby

I was wondering if there is a Ruby equivalent of JavaScript's fromCharCode function. What it does is converting Unicode values into characters.

Here an example of its return value in JavaScript:

String.fromCharCode(72,69,76,76,79)
#=> HELLO

Is there an equivalent for that in Ruby?

like image 478
Severin Avatar asked Sep 16 '25 23:09

Severin


1 Answers

Use Integer#chr:

72.chr
# => "H"
[72,69,76,76,79].map{|i| i.chr }.join
# => "HELLO"
[72,69,76,76,79].map(&:chr).join
# => "HELLO"

UPDATE

Without parameters chr only handles 8-bit ASCII characters, you have to pass the parameter Encoding::UTF_8 to chr to handle Unicode characters.

512.chr
RangeError: 512 out of char range
        from (irb):8:in `chr'
        from (irb):8
        from /usr/bin/irb:12:in `<main>'

512.chr(Encoding::UTF_8)
# => "Ȁ"
[512,513].map{|i| i.chr(Encoding::UTF_8)}.join
# => "Ȁȁ"
like image 133
falsetru Avatar answered Sep 19 '25 15:09

falsetru