Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

charCodeAt() equivalent in Ruby

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?

like image 837
Severin Avatar asked Jan 13 '14 10:01

Severin


1 Answers

You can use the String#[] and String#ord methods:

'HELLO WORLD'[-1].ord
# => 68

It also handles Unicode characters:

'aā'[1].ord
# => 257
like image 160
toro2k Avatar answered Oct 19 '22 19:10

toro2k