Ruby中字符的ASCII值

Lak*_*osI 21 ruby ascii character

如何在Ruby 1.9中获取字符的ASCII值?

我在网上广泛搜索,但没有成功.我试过?x和"x"[0],但他们返回的只是"x".

Mar*_*off 46

String#ord方法将起到作用:

ruby-1.9.2-p136 > 'x'.ord
 => 120 
ruby-1.9.2-p136 > '0'.ord
 => 48 
ruby-1.9.2-p136 > ' '.ord
 => 32 
Run Code Online (Sandbox Code Playgroud)


小智 17

你也可以使用

ruby-2.0.0p353 > "x".sum
=> 120

ruby-2.0.0p353 > "a string".sum
=> 792 
Run Code Online (Sandbox Code Playgroud)

'sum'方法将找到所有字符代码的总和,但如果只放置一个字符,它将仅为您提供该字符的代码.

  • 似乎 .ord 也需要正确的 UTF-8,但 .sum 并不关心。 (2认同)