views:

1222

answers:

4

I'm a little confused about when to use single quoted strings versus double quoted strings. I've noticed that if I put a variable inside a single quoted string, it doesn't get interpreted. Also, if I use a newline character in a double quoted string, it causes the string to be displayed over two lines whereas in a single quoted string the newline just appears as text within the string - the string is not displayed over two lines.

When it comes to backslashes, though, I'm not sure what's going on. If I add a backslash+space to the start of a string I get a different result:

"\ 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 the '\ ' 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 basic rule that would help to explain the fundamental difference between how single quoted strings and double quoted strings handle backslashes in Ruby?

+5  A: 

I'd refer you to this page for a very concise yet comprehensive overview of the differences.

zvoase
A: 

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

Yes. Single-quoted strings are treated as literals; double-quoted strings are interpolated. This is the same in other Ruby-like languages, and hasn't changed in 1.9.

bzlm
+4  A: 

Double-quoted strings support the full range of escape sequences, as shown below:

  • \a Bell/alert (0x07)
  • \b Backspace (0x08)
  • \e Escape (0x1b)
  • \f Formford (0x0c)
  • \n Newline (0x0a)
  • \r Return (0x0d)
  • \s Space (0x20)
  • \t Tab (0x09)
  • \v Vertical tab (0x0b)

For single-quoted strings, two consecutive backslashes are replaced by a single backslash, and a backslash followed by a single quote becomes a single quote.

'escape using "\\"' -> escape using "\"
'That\'s right'     -> That's right
John Topley
+1  A: 

This is not a full answer (since the simple question has been answered already), but rather it is supplementary information.

http://stackoverflow.com/questions/279270/which-style-of-ruby-string-quoting-do-you-favour

Don't use double quotes if you have to escape them. And don't fall in "single vs double quotes" trap. Ruby has excellent support for arbitrary delimiters for string literals:

http://rors.org/2008/10/26/dont-escape-in-strings

I took that advice and have never looked back!

Ian Terrell