简体   繁体   中英

ASCII value of character in Ruby

How do I obtain the ASCII value of a character in Ruby 1.9?

I searched the Inte.net far and wide, but without success. I tried?x and "x"[0], but all they return is "x".

The String#ord method will do the trick:

ruby-1.9.2-p136 > 'x'.ord
 => 120 
ruby-1.9.2-p136 > '0'.ord
 => 48 
ruby-1.9.2-p136 > ' '.ord
 => 32 

You can also use

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

ruby-2.0.0p353 > "a string".sum
=> 792 

The 'sum' method will find the sum of all character codes, but if you put only one character it will give you the code of that one only.

I was also stuck with this, ord only works from string to number and not vice versa. The solution is:

def getChar(a):
 return a.chr
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM