tags:

views:

2078

answers:

3

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, 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? any ideas?

+1  A: 

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.

dorr
It's better to edit your original post instead of posting a separated reply to your own question.
pierr
@pierr - But this is an answer to the question, not just an update of the question
rampion
The methods aren't broken. Ruby 1.9 defines their behavior differently, as Chuck explained.
Telemachus
Yeah, broken was the wrong word. They no longer work as I expected based on previous versions.The new usage was what I originally expected them to do, and makes a lot more sense.
dorr
+8  A: 

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).

Chuck
+2  A: 

For 1.8 and 1.9

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

or

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