前缀的意义是什么? Ruby 1.9 中的运算符
我只是想知道它有什么应用。我相信 1.9 前缀?将返回该字符的字符串版本。
?a #=> "a"
?\t #=> "\t"
这只是“a”或“\t”的简写吗?
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 #=> "\t"
Is this just shorthand for 'a' or '\t'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
主要是为了向后兼容。在 1.9 之前的版本中,
?
计算结果为与相关字符的 ASCII 值相对应的Fixnum
。对String
进行索引还返回一个Fixnum
。因此,例如,如果您想检查字符串的第三个字符是否是字母“a”,您可以
在 Ruby 1.9 中执行此操作,字符串不再被视为固定数字数组,而是被视为字符迭代器(单-实际上是字符串)。因此,上述代码将不再有效:
s[2]
将是一个字符串,?a
将是一个数字,并且这两个永远不会相等。因此,
?
也被更改为计算为单字符字符串,以便上面的代码继续工作。It's mainly for backwards compatibility. In versions prior to 1.9,
?
evaluated to aFixnum
corresponding to the ASCII value of the character in question. Indexing into aString
also returned aFixnum
.So, if you wanted to check, for example, if the third character of a string was the letter 'a' you would do
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.在 ruby 1.8 及更早版本
中将返回 'a' 字符的 ASCII 版本。
在 1.9 中它只返回字符串(正如你所假设的那样)
in ruby 1.8 and earlier
would return the ASCII version of 'a' char.
in 1.9 it just returns the string ( just as you've assumed )
你是对的,你得到了字符的字符串值。以前用于获取字符的 ASCII 值。
You are correct, you get the string value of the characters. It was previously used to get the ASCII value of the characters.