问题
When you do ?a
in ruby 1.8.7 you used to get the ASCII character of 'a'
in ruby 1.9.2 this code returns
> ?a
> "a"
What is the significance of this, and what does the output in 1.9.2 mean
回答1:
In Ruby 1.8 "foo"[0]
returned the character code at index 0 instead of the character string at index 0. As part of support for international strings with various encodings (instead of as an array of bytes), Ruby 1.9 changed this behavior to return the single-character string at the specified index.
Along with this change, ?a
was changed to evaluate as a single-character string as well. Presumably this was so that libraries with code like this...
if my_string[0] == ?a
...would continue to work. If you want character code value for the first character of a string, use String#ord:
puts "It's a boy!" if my_string[0].ord == 89
For a lot more answer, see this stackoverflow question.
来源:https://stackoverflow.com/questions/4363067/why-does-the-a-command-in-ruby-1-9-2-does-not-return-ascii-code