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

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


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]