'ASCII value of character in Ruby

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

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



Solution 1:[1]

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.

Solution 2:[2]

x.ord

http://www.ruby-doc.org/core/classes/String.html#M001177

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sh.K
Solution 2 randomguy
Solution 3 Suraj Rao