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?
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
# => "Ȁȁ"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With