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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With