giwook
giwook

Reputation: 580

When would you use single-quote strings over double-quote strings in Ruby?

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.

Upvotes: 2

Views: 47

Answers (2)

Thilo
Thilo

Reputation: 262584

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"

Upvotes: 3

B Seven
B Seven

Reputation: 45943

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.

Upvotes: 3

Related Questions