Getting an ASCII character code in Ruby using `?` (question mark) fails
I'm in a situation where I need the ASCII value of a character (for Project Euler question #22, if you want to get specific) and I'm running into an issue.
Being new to ruby, I googled it, and found that ?
was the way to go: ?A
or whatever. But when I incorporate it into my code, the result of that statement is the string "A"
—no character code. Same issue with [0]
and slice(0)
, both of which should theoretically return the ASCII code.
The only thing I can think of is that this is a ruby version issue. I'm using 1.9.1-p0, having upgraded from 1.8.6 this afternoon. I cheated a little going from a working version of Ruby, in the same directory, I figured I probably already had the files that don't come bundled with the .zip file, so I didn't download them.
So why exactly are all my ASCII codes being turned into actual characters?
Solution 1:
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).
Solution 2:
How about
"a"[0].ord
for 1.8/1.9 portability.
Solution 3:
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
Solution 4:
For 1.8 and 1.9
?a.class == String ? ?a.ord : ?a
or
"a".class == String ? "a".ord : "a"[0]
Solution 5:
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.