Search code examples
rubystringsyntaxconvention

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.


Solution

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