What's the Point of the prefix ? operator in Ruby 1.9

前端 未结 3 1004
天涯浪人
天涯浪人 2020-12-12 05:25

I\'m just wondering what applications it has. I believe in 1.9 the prefix ? would return the string version of that character.

?a   #=> \"a\"
?\\t  #=>         


        
相关标签:
3条回答
  • 2020-12-12 05:50

    You are correct, you get the string value of the characters. It was previously used to get the ASCII value of the characters.

    0 讨论(0)
  • 2020-12-12 06:11

    It's mainly for backwards compatibility. In versions prior to 1.9, ? evaluated to a Fixnum corresponding to the ASCII value of the character in question. Indexing into a String also returned a Fixnum.

    So, if you wanted to check, for example, if the third character of a string was the letter 'a' you would do

    s[2] == ?a
    

    In Ruby 1.9, strings are no longer treated as an array of fixnums but as an iterator of characters (single-character strings, actually). As a result, the above code would no longer work: s[2] would be a string, ?a would be a number, and those two would never be equal.

    Therefore, ? was also changed to evaluate to a single-character string, so that the above code continues to work.

    0 讨论(0)
  • 2020-12-12 06:14

    in ruby 1.8 and earlier

    ?a 
    

    would return the ASCII version of 'a' char.

    in 1.9 it just returns the string ( just as you've assumed )

    0 讨论(0)
提交回复
热议问题