I had a good look around but I couldn't find the convention on how to use quotes for strings. I know the difference between the two, but everywhere I see good code with double quotes where the singles are enough. Therefor, I can't recognize any pattern. I'm asking this because I'd like to start contributing to open-source and I'd like to get a good habit since the beginning. I rather use the single quotes as much as possible, also to strengthen my confidence with the difference between the two.
What you probably already know:
There's no significant performance difference.
Using double quotes is helpful so you can use apostrophes without having to worry about escaping them inside the string thus making the string look 'prettier' in the code. Think "Don't do that"
vs 'Don\'t do that'
There's a line of thought that states that you should never escape in strings. If you need single quotes and double quotes inside your string, you are better off using a heredoc or flexible quotes. In the end, I'd let that guide what you need to use when coding if evaluating ruby code inside the string is not a concern.
I don't think there is a strong convention within the entire community. From what I have seen, there seems to be a bias towards ignoring single quotes altogether and always using double quotes. In some circles, that is even a convention, but a localized one, not one for the whole community.
Personally, whenever I have several different ways to express the same thing, I tend to use those different ways to convey different semantics. (For example, I use curly braces vs. do
/end
in blocks to distinguish between blocks that are used for their side effects and blocks that are used for their return value.)
So, I only use double quotes when I actually want to use string interpolation or escaping, otherwise I use single quotes. That way, when I see a string I can immediately tell that there's no funny business going on, and there's no code hidden inside of it.
I am pragmatic, though. I very much prefer "It's a string!"
over 'It\'s a string!'
or %q[It's a string!]
.
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