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

前端 未结 4 540
傲寒
傲寒 2020-11-29 10:55

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

I see the following works:

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


        
相关标签:
4条回答
  • 2020-11-29 11:26

    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.

    0 讨论(0)
  • 2020-11-29 11:35

    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).

    0 讨论(0)
  • 2020-11-29 11:37

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

    0 讨论(0)
  • 2020-11-29 11:38

    “?” 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

    0 讨论(0)
提交回复
热议问题