I was wondering if there is a Ruby equivalent of JavaScript's charCodeAt()
method. The charCodeAt()
method returns the Unicode value of the character at the specified index in a string.
The following example returns the Unicode value of the last character in a string:
str.charCodeAt("HELLO WORLD".length-1)
#=> 68
Is there an equivalent for that in Ruby?
You can use the String#[]
and String#ord
methods:
'HELLO WORLD'[-1].ord
# => 68
It also handles Unicode characters:
'aā'[1].ord
# => 257
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