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

后端 未结 6 1003
旧时难觅i
旧时难觅i 2020-12-08 06:01

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 n

相关标签:
6条回答
  • 2020-12-08 06:44

    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.

    0 讨论(0)
  • 2020-12-08 06:47

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

    0 讨论(0)
  • 2020-12-08 06:52

    How about

    "a"[0].ord
    

    for 1.8/1.9 portability.

    0 讨论(0)
  • 2020-12-08 06:57

    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    
    
    0 讨论(0)
  • 2020-12-08 07:01

    If you read question 22 from project Euler again you'll find you you are not looking for the ASCII values of the characters. What the question is looking for, for the character "A" for example is 1, its position in the alphabet where as "A" has an ASCII value of 65.

    0 讨论(0)
  • 2020-12-08 07:03

    For 1.8 and 1.9

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

    or

    "a".class == String ? "a".ord : "a"[0]
    
    0 讨论(0)
提交回复
热议问题