"foo"[0] = ?b # "boo"
我正在查看上面的示例并试图弄清楚:
- “?b”如何暗示字符“b”?
为什么有必要? - 我不能只写这个吗:
"foo"[0] = 'b' # "boo"
最佳答案
Ed Swangren: ? returns the character code of a character.
在 Ruby 1.9 中没有。从 1.9 开始,?a
返回 'a'。看这里:Son of 10 things to be aware of in Ruby 1.9!
telemachus ~ $ ~/bin/ruby -v
ruby 1.9.1p0 (2009-01-30 revision 21907) [i686-linux]
telemachus ~ $ ~/bin/ruby -e 'char = ?a; puts char'
a
telemachus ~ $ /usr/bin/ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]
telemachus ~ $ /usr/bin/ruby -e 'char = ?a; puts char'
97
编辑:非常对 changes in Ruby 1.9 的完整描述.
另一个编辑:请注意,如果您希望通过 ?a
在 1.8 中将字符串转换为数字,您现在可以使用 'a'.ord
。
关于ruby - 为什么 "?b"在 Ruby 中表示 'b'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/656610/