Ruby中的charCodeAt()等价物

Sev*_*rin 6 ruby character-encoding

我想知道是否有一个类似于JavaScript的Ruby charCodeAt()方法.该charCodeAt()方法返回字符串中指定索引处的字符的Unicode值.

以下示例返回字符串中最后一个字符的Unicode值:

str.charCodeAt("HELLO WORLD".length-1)
#=> 68
Run Code Online (Sandbox Code Playgroud)

Ruby中有相同的东西吗?

tor*_*o2k 8

您可以使用String#[]String#ord方法:

'HELLO WORLD'[-1].ord
# => 68
Run Code Online (Sandbox Code Playgroud)

它还处理Unicode字符:

'a?'[1].ord
# => 257
Run Code Online (Sandbox Code Playgroud)