前缀的意义是什么? Ruby 1.9中的运算符 [英] What's the Point of the prefix ? operator in Ruby 1.9

查看:92
本文介绍了前缀的意义是什么? Ruby 1.9中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道它具有什么应用程序.我相信1.9的前缀吗?将返回该字符的字符串版本.

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"

这只是'a'或'\ t'的简写吗?

Is this just shorthand for 'a' or '\t'?

推荐答案

主要是为了向后兼容.在1.9之前的版本中,?评估为与所讨论字符的ASCII值相对应的Fixnum.索引到String 还会返回Fixnum.

It's mainly for backwards compatibility. In versions prior to 1.9, ? evaluated to a Fixnum corresponding to the ASCII value of the character in question. Indexing into a String also returned a Fixnum.

因此,例如,如果您要检查字符串的第三个字符是否为字母"a",则可以这样做

So, if you wanted to check, for example, if the third character of a string was the letter 'a' you would do

s[2] == ?a

在Ruby 1.9中,字符串不再被视为fixnum的数组,而是字符的迭代器(实际上是单字符字符串).结果,上面的代码将不再起作用: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). 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.9中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆