Double vs single quotes Double vs single quotes ruby ruby

Double vs single quotes


" " allows you to do string interpolation, e.g.:

world_type = 'Mars'"Hello #{world_type}"


except the interpolation, another difference is that 'escape sequence' does not work in single quote

puts 'a\nb' # just print a\nb puts "a\nb" # print a, then b at newline 


There is a difference between single '' and double quotes "" in Ruby in terms of what gets to be evaluated to a string.

Initially, I would like to clarify that in the literal form of a string whatever is between single or double quotes gets evaluated as a string object, which is an instance of the Ruby String class.

Therefore, 'stackoverflow' and "stackoverflow" both will evaluate instances of String class with no difference at all.

The difference

The essential difference between the two literal forms of strings (single or double quotes) is that double quotes allow for escape sequences while single quotes do not!

A string literal created by single quotes does not support string interpollation and does not escape sequences.

A neat example is:

"\n" # will be interpreted as a new line

whereas

'\n' # will display the actual escape sequence to the user

Interpolating with single quotes does not work at all:

'#{Time.now}'=> "\#{Time.now}" # which is not what you want..

Best practice

As most of the Ruby Linters suggest use single quote literals for your strings and go for the double ones in the case of interpolation/escaping sequences.