Getting ASCII character code in Ruby using `?` (Question Mark) fails

I am in a situation where I need the ASCII value of a character (for Project Euler question # 22 , if you want to get it), and I ran into a problem.

Being new to rubies, I searched for it and found that ? Is this the way ?A or something else. But when I include it in my code, the result of this statement is the character string "A" -no. Same problem with [0] and slice(0) , both of which should theoretically return ASCII code.

The only thing I can think of is the problem with the ruby ​​version. I am using 1.9.1-p0 updated with 1.8.6 in the afternoon. I changed the work with the working version of Ruby a bit, in the same directory, I assumed that I probably already have files that are not included in the package .zip file, so I did not download them.

So why exactly are all my ASCII codes converted to valid characters?

+42
ruby char ascii
Aug 13 '09 at 5:41
source share
6 answers

Ruby up to 1.9 processed characters is somewhat inconsistent. ?a and "a"[0] return an integer representing the value of the ASCII character (which was usually not what people were looking for), but in practical use, characters are usually represented by a single-character string. In Ruby 1.9, characters never mysteriously turn into integers. If you want to get the value of an ASCII character, you can use the ord method, for example ?a.ord (which returns 97).

+62
Aug 13 '09 at 5:53
source share

What about

 "a"[0].ord 

for portability 1.8 / 1.9.

+31
Nov 15 '10 at 18:34
source share

For 1.8 and 1.9

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

or

 "a".class == String ? "a".ord : "a"[0] 
+10
Feb 23 '10 at 8:13
source share

Found a solution. "string" .ord returns the ascii code s. It seems that the methods I found were broken down into a 1.9 series of rubies.

+7
Aug 13 '09 at 5:51
source share

Ruby Programming / ASCII

In the previous version of ruby ​​before 1.9, you can use the question mark syntax.

 ?a 

After 1.9, we use ord instead.

 'a'.ord 
+4
Sep 02 '14 at 3:01
source share

If you read question 22 again from the Euler project, you will find that you are not looking for ASCII character values. The question that this question asks for the symbol "A", for example, is 1, its position in the alphabet, where "A" has the value ASCII 65.

-2
Sep 04 '13 at 2:09 on
source share



All Articles