2

Ruby newbie here, and I understand that single-quote strings will not allow interpolation and will ignore most escape sequences. I'm just looking for some actual examples of when you might want to use single-quote strings as opposed to double-quote strings.

giwook
  • 570
  • 4
  • 11
  • 23
  • possible duplicate of [Which style of Ruby string quoting do you favour?](http://stackoverflow.com/questions/279270/which-style-of-ruby-string-quoting-do-you-favour) – infused May 13 '15 at 04:31

2 Answers2

3

Single quotes are used when you don't need interpolation:

name = 'joe'

Double is used when you do need interpolation:

name = 'joe'
puts "The name is #{name}"

You can use double quotes in both cases. Many people find it simpler to use double quotes all the time.

You are correct about escape sequences.

puts "\nThis is a new line."
=>
=> This is a new line.

puts '\nThis is a new line.'
 => '\nThis is a new line.'

I prefer to use single quotes whenever possible, because double quotes are noisy.

B Seven
  • 44,484
  • 66
  • 240
  • 385
3

In addition to the difference in interpolation, it is also nice to be able to include quotes in the string literal without clumsy escapes. Just choose the opposite surrounding quotes:

name = 'Phil "the man" Smith'
name = "Jack O'Conner"
Thilo
  • 257,207
  • 101
  • 511
  • 656