Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an ASCII character code in Ruby using `?` (question mark) fails

Tags:

char

ruby

ascii

People also ask

What is the ascii value of empty string?

Returns the ASCII code for the first character of a string. If the string is empty, a value of 0 is returned.


Ruby before 1.9 treated characters somewhat inconsistently. ?a and "a"[0] would return an integer representing the character's ASCII value (which was usually not the behavior people were looking for), but in practical use characters would normally be represented by a one-character string. In Ruby 1.9, characters are never mysteriously turned into integers. If you want to get a character's ASCII value, you can use the ord method, like ?a.ord (which returns 97).


How about

"a"[0].ord

for 1.8/1.9 portability.


For 1.8 and 1.9

?a.class == String ? ?a.ord : ?a

or

"a".class == String ? "a".ord : "a"[0]

Ruby Programming/ASCII

In previous ruby version before 1.9, you can use question-mark syntax.

?a

After 1.9, we use ord instead.

'a'.ord    

Found the solution. "string".ord returns the ascii code of s. Looks like the methods I had found are broken in the 1.9 series of ruby.