Why does the ?a command in ruby 1.9.2 does not return ASCII code

两盒软妹~` 提交于 2019-12-11 09:24:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!