Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby coding convention for single or double quoting your strings

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.

like image 604
ecoologic Avatar asked Jan 25 '11 22:01

ecoologic


2 Answers

What you probably already know:

  • Single quotes are just fine for simple strings.
  • If you need to evaluate anything inside the string, you'll need double quotes.

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.

like image 154
Shaun Avatar answered Oct 25 '22 22:10

Shaun


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!].

like image 31
Jörg W Mittag Avatar answered Oct 25 '22 20:10

Jörg W Mittag