Tucker Tucker - 10 months ago 54
Ruby Question

Backslashes in single quoted strings vs. double quoted strings

If I add a backslash+space to the start of double and single quoted strings, I get different results:

"\ text"
'\ text'

In the output for the double quoted string I see only a space.

In the output for the single quoted string I see backslash+space.

What's happening there? Is this because
'\ '
is interpreted as a special character in the double quote string but in the single quoted string the characters are preserved as is?

If I change the strings to this, I see the same output, namely a single slash followed by a space and then the text:

"\\ text"
'\\ text'

In both cases the backslash is escaped. I'm confused why they work the same way in this situation.

Is there some rule that would help to explain the fundamental difference between how single quoted strings and double quoted strings handle backslashes in Ruby?

Answer Source

I'd refer you to "Ruby Programming/Strings" for a very concise yet comprehensive overview of the differences.

From the reference:

puts "Betty's pie shop"

puts 'Betty\'s pie shop'

Because "Betty's" contains an apostrophe, which is the same character as the single quote, in the second line we need to use a backslash to escape the apostrophe so that Ruby understands that the apostrophe is in the string literal instead of marking the end of the string literal. The backslash followed by the single quote is called an escape sequence.