0

I ran across a code snippet today that used the ? operator to quote the next character. I have no idea where the documentation is for this method and really no idea what it's actually doing.

I've looked at the ruby docs, but haven't found it.

?1

=> "1"

?1"23abc"

=> "123abc"

1 Answers1

4

? is not a method in this case but rather a parsable syntax. ? is a character literal in this context

Docs Excerpt:

There is also a character literal notation to represent single character strings, which syntax is a question mark (?) followed by a single character or escape sequence that corresponds to a single codepoint in the script encoding:

?a       #=> "a"
?abc     #=> SyntaxError
?\n      #=> "\n"
?\s      #=> " "
?\\      #=> "\\"
?\u{41}  #=> "A"
?\C-a    #=> "\x01"
?\M-a    #=> "\xE1"
?\M-\C-a #=> "\x81"
?\C-\M-a #=> "\x81", same as above
?あ      #=> "あ"

You have also found another fun little mechanism of the parser which is 2 Strings can be concatenated together by simply placing them side by side (with or without white space). e.g.

"1" "234" 
#=> "1234"
"1""234"
#=> "1234"
engineersmnky
  • 25,495
  • 2
  • 36
  • 52
  • I actually found that in ruby 1.8 and prior, this returns the Ascii number. ```ruby :001 > ?1 => 49 ``` Good to know about the string concatenation, that's the first I've heard of that. – Andrew Merritt Jun 11 '19 at 19:20
  • @AndrewMerritt I sincerely hope you are not using 1.8 or really anything less than 2.3 (EOL 2019-03-31) but yes technically speaking < 1.9 returned the ASCII number – engineersmnky Jun 11 '19 at 19:24
  • Haha, no I'm using 2.5.x in my projects. Just found it to be an interesting tidbit. Apparently I missed the previous question my search, which also shows that same answer. – Andrew Merritt Jun 11 '19 at 19:26