简体   繁体   English

前缀的意义是什么? Ruby 1.9中的运算符

[英]What's the Point of the prefix ? operator in Ruby 1.9

I'm just wondering what applications it has. 我只是想知道它有什么应用程序。 I believe in 1.9 the prefix ? 我相信1.9的前缀吗? would return the string version of that character. 将返回该字符的字符串版本。

?a   #=> "a"
?\t  #=> "\t"

Is this just shorthand for 'a' or '\\t'? 这只是'a'或'\\ t'的简写吗?

It's mainly for backwards compatibility. 主要是为了向后兼容。 In versions prior to 1.9, ? 在1.9之前的版本中, ? evaluated to a Fixnum corresponding to the ASCII value of the character in question. 求值为与所讨论字符的ASCII值相对应的Fixnum Indexing into a String also returned a Fixnum . 索引到String 返回一个Fixnum

So, if you wanted to check, for example, if the third character of a string was the letter 'a' you would do 因此,例如,如果您要检查字符串的第三个字符是否为字母“ a”,则可以执行

s[2] == ?a

In Ruby 1.9, strings are no longer treated as an array of fixnums but as an iterator of characters (single-character strings, actually). 在Ruby 1.9中,字符串不再被视为fixnum的数组,而是字符的迭代器(实际上是单字符字符串)。 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. 结果,上面的代码将不再起作用: s[2]将是一个字符串, ?a将是一个数字,并且那两个永远不会相等。

Therefore, ? 因此, ? was also changed to evaluate to a single-character string, so that the above code continues to work. 还更改为计算为单个字符的字符串,因此上述代码继续有效。

in ruby 1.8 and earlier 在ruby 1.8及更早版本中

?a 

would return the ASCII version of 'a' char. 将返回ASCII版本的'a'char。

in 1.9 it just returns the string ( just as you've assumed ) 在1.9中,它只是返回字符串(就像您假设的那样)

You are correct, you get the string value of the characters. 您是正确的,您获得了字符的字符串值。 It was previously used to get the ASCII value of the characters. 以前用于获取字符的ASCII值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM