What does the unary question mark (?) operator do?

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

I see the following works:

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

And this doesn't work:

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

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

questions:

  1. What does this operator do?
  2. When should one use it?
  3. If it really only creates a one-character string, why was it included in the language? Doesn't it break the language orthogonality? What is the benefit?

Answers 1

  • 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".


Related Articles