简体   繁体   中英

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?

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's not an operator, it's a character literal. However, there is no character type in Ruby, so instead of an instance of a character type the character literal evaluates to the "default representation of a character". In Ruby 1.9+, that's a String of length 1, in Ruby 1.8, it's a Fixnum denoting the Unicode codepoint of the character.

Re #2, a place I've found it useful is in conveying that a parameter I'm setting or value I'm testing for is intended to be a single character and not just that this happened to simply be a short string. It's a subtle readability/documentation thing, but worth considering for later maintainers (including myself).

“?” mark in a ruby method indicates that method will return either true or false.

After checking method name we can determine that this method is going to return boolean value.

Example:

empty? - This method will check whatever the object is empty or not. Depending on that it will return true or false.

Uses:

[1,2,3].empty? - return false

[].empty? - return true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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