34

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?
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
fotanus
  • 19,618
  • 13
  • 77
  • 111

4 Answers4

30

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

sawa
  • 165,429
  • 45
  • 277
  • 381
  • Thanks sawa, you can read about orthogonality here: en.wikipedia.org/wiki/Orthogonality_(programming) - by some weird reason can't make a markdown link with it. – fotanus May 20 '13 at 05:15
  • 1
    But how does a character literal break orthogonality whereas an array literal, map literal, string literal, lambda literal, integer literal, symbol literal, float literal etc. doesn't? – Jörg W Mittag May 20 '13 at 08:30
13

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
2

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

user2391694
  • 161
  • 1
  • 5
-3

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

Poonkodi
  • 140
  • 1
  • 9