I encountered a rather peculiar behavior of strings today.
Here is my irb session:
irb(main):001:0> ‘ab\c’
irb(main):002:0’ ’
SyntaxError: compile error
(irb):2: unterminated string meets end of file
from (irb):2
irb(main):003:0> ‘ab\c’
=> “ab\c”
irb(main):004:0> ‘a\b’
=> “a\b”
irb(main):005:0>
As you can see when I typed ‘ab\c’ my irb didn’t return. It was
expecting some thing more. Then I typed a single quote ( ’ ) to
terminate the string and it gave me this SyntaxError. The same thing
happens even I type ‘ab\c’
I was trying this after reading section 3.2.1.1 of “The Ruby
Programming Language”. This is what it says about backslashes in
single quoted strings:
"In single-quoted strings, a backslash is not special if the character
that follows it is anything other than a quote or a backslash. "
But at the same time if I type ‘a\b’ it returns ‘a\b’ which is inline
with the book. Any ideas what’s happening here?
I think you stumbled on another special character, \c, which seems to
have some weird properties:
-in single quotes, must be followed by another character, but when it
is, just swaps the \ for a \
-in double quotes, again must be followed by another character, which it
translates into a number, though by what scheme i have no idea:
In a double-quoted string, \c followed by another character forms a
control character. Control characters are character codes 0 to 31 in
the ASCII character set. When you call inspect on a string (as irb
does for you), Ruby escapes these control characters and those are the
number you are seeing.
In a single-quoted string, \c doesn’t do anything, just like “The Ruby
programming language” says. Irb gets confused here and does interpret
the \c, thinks the string goes on while it doesn’t, asks more input
until a quote is given, which really starts a new string which is then
unterminated and that’s the error you get.
You would have to know what \c means to find this out, though! That’s
like saying the answer is in the index but the question isn’t…if you
know what i mean.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.