I understand the functional difference between single and double quotes in Ruby, but I'm wondering what concrete reasons people have for varying between the two. In my mind it seems like you should just always use a double quote, and not think about it.
A couple rationales that I've read in researching the topic...
Use a single quote unless a double quote is required.
There's a very, very minor performance advantage to a single quotes.
Any other interesting thoughts out there? (Or maybe this is a case of the freedom or Ruby leaving the door open for no One Right Way to do something...)
Single-quoted Strings: It is the easiest way to define a string. You can use it when you want the string to be exactly as it is written. All the escape sequences like \r or \n, will be output as specified instead of having any special meaning. Single-quote is usually faster in some cases.
If you've written Ruby, you've heard it before: Use single quoted strings unless you need string interpolation.
The basic difference between these two methods is Single quotes can not hold/print escape sequences directly, while double quotes can. i.e. Double quoted strings are used for String Interpolation in Ruby.
I usually follow the following rule:
never use double quotes (or
%Q
or%W
) if you don't interpolate
The reason for this is that if you're trying to track down an error or a security bug, you immediately know when looking at the beginning of the string that there cannot possibly any code inside it, therefore the bug cannot be in there.
However, I also follow the following exception to the rule:
use double quotes if they make the code more readable
I.e. I prefer
"It's time"
over
'It\'s time'
%q{It's time}
It is technically true that single quoted strings are infinitesimally faster to parse than double quoted strings, but that's irrelevant because
So, the answer to your question is: Yes, there is an advantage, namely that you can spot right away whether or not a string may contain code.
I can think of three reasons to use single quoted strings:
'he said "yes"'
vs "he said \"yes\""
)I would assume using a single-quoted string is faster, since double quotes allow string interpolation, and single-quoted strings do not.
That's the only difference I know of. For that reason, it's probably best to only use a single-quoted string unless you need string interpolation:
num = 59
"I ate #{num} pineapples"`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With