Reputation: 7719
Just curious what's behind the decision of the Ruby developers to interpret the double-backslash escape sequence inside single quotes. I can understand why an escaped single-quote has to be interpreted because insertion of single-quote character won't be possible. For example:
'\'' == "'"
But consider '\\' == "\\"
. Why is this another special case?
Upvotes: 2
Views: 5665
Reputation: 146053
The one escape initially needed in hard-quoted strings is \'
, as others also note.
But the real, fundamental reason why \\
is also needed is because, once \'
is supported, it otherwise would not be possible to end a hard-quoted string with a backslash.
Upvotes: 2
Reputation: 84343
This special case is necessary to embed single quotes or apostrophes into a single-quoted string. Consider the following:
'\''
# => "'"
'It\'s a baby boy!'
# => "It's a baby boy!"
Without the escape, Ruby will assume that the second quote mark terminates the string, leaving you with an unbalanced third quote mark.
As a corollary of the previous, you need to escape the escape character to avoid escaping the subsequent character. For example, '\'
says to escape the second quote mark, leaving you with an unterminated string. However, '\\'
results in a literal slash within the string.
Upvotes: 0
Reputation: 230296
This is to insert the backslash itself. If there was no such special case, it wouldn't be possible to have backslashes in single-quoted strings.
\'
and \\
are the only two escape sequences in single-quoted strings.
Upvotes: 1