David Unric
David Unric

Reputation: 7719

Why is a double-backslash escape required inside single-quoted strings?

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

Answers (3)

DigitalRoss
DigitalRoss

Reputation: 146053

In order to end a String with a backslash

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

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Escape Required for Apostrophes

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.

Escape Required for Slashes

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

Sergio Tulentsev
Sergio Tulentsev

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

Related Questions