steveyang
steveyang

Reputation: 9288

Inconsistent escaping behavior of single quote string

The escaping rule for single quoted string looks inconsistent in the following example: What's the exactly rules does Ruby escape single quoted string?

p str1 = 'a\b\c'
#=> "a\\b\\c" looks fine, I know single quotes don't do escaping
p str2 = 'a\\b\\c'
#=> "a\\b\\c" hmm? It actually escapes

# Trying double quotes
p str3 = "a\b\c" 
#=> Error, \c isn't valid
p str4 = "a\\b\\c"
#=> "a\\b\\c" 

p str1 == str4, str2 == str4
# true, true

Upvotes: 2

Views: 185

Answers (1)

sgtFloyd
sgtFloyd

Reputation: 1007

Single quoted strings only support two escape sequences:
\' – single quote
\\ – single backslash
Except for these two escape sequences, everything else between single quotes is treated literally.

source: wikibooks

Upvotes: 3

Related Questions