一元问号(?)运算符的作用是什么? [英] What does the unary question mark (?) operator do?

查看:121
本文介绍了一元问号(?)运算符的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HAML代码中看到了此运算符.我不知道这是干什么的.

I saw this operator in HAML code. I wonder what it is for.

我看到以下作品:

> ?{
=> "{" 
> ?\s
=> " " 
> ?a
=> "a" 

这不起作用:

> ?ab
SyntaxError: (irb):4: syntax error, unexpected '?'

所以我假设它接受一个字符作为参数,并返回带有该字符的字符串.

So I suppose that it takes a character a argument and returns a string with that character.

问题:

  1. 该操作员做什么?
  2. 什么时候应该使用它?
  3. 如果它实际上仅创建一个单字符字符串,为什么将其包含在语言中?它不会破坏语言的正交性吗?有什么好处?

推荐答案

它返回一个字符串.这是编写单字符字符串文字的最短方法.当您要定义很多单字符字符串时,请使用它.它是Ruby< 1.9的继承者,它用于返回该字符的ASCII代码.我不明白您所说的打破语言正交性"是什么意思.

It returns a single character string. It is the shortest way to write a single-character string literal. Use it when you want to define a lot of single-character strings. It is a heritage from Ruby <1.9, where it used to return the ASCII code for that character. I don't understand what you mean by "break the language orthogonality".

这篇关于一元问号(?)运算符的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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