Backslashes in single quoted strings vs. double quoted strings

Solution 1:

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

Solution 2:

Ruby only interprets escape sequences in double quoted strings. In a single quoted string, only \\ (backslash backslash) and \' (backslash quote) are taken as special characters. You should use double quoted strings only when you need more interpretation. Otherwise, single quotes provide a performance boost.

When you mentioned including the name of a variable, Ruby never does that. Just the variable name is treated as more of the string literal. To include the value of a variable (or any expression) put the expression in like this:

"#{variable}"

Note that this only works in double quoted strings. To add a variable to a single quoted one, you need to do this:

'The value of X is: '+X

If you need serious formatting, look into Ruby's version of sprintf and printf. They are pretty much wrappers around the C functions, and are quite powerful, but a bit cumbersome to use.

Solution 3:

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.

Solution 4:

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

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!