开发者

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

When you do ?a in ruby 1.8.7 you used to get the ASCII c开发者_JS百科haracter 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜