Ruby coding for single or double quoted strings

I had a good appearance, but I could not find an agreement on how to use quotation marks for strings. I know the difference between the two, but everywhere I see good double-quoted code where there are enough singles. Therefore, I cannot recognize any pattern. I ask about this because I would like to start participating in open-source, and from the very beginning I would like to get a good habit. I rather use single quotes as much as possible, also to strengthen my confidence in the difference between the two.

+6
string syntax ruby convention
source share
2 answers

I don’t think there is a strong convention in the whole community. From what I saw, there seems to be a bias towards ignoring single quotes in general and always using double quotes. In some circles, this is even a convention, but a localized one, and not one for the entire community.

Personally, whenever I have several different ways to express the same thing, I tend to use these different ways to convey different semantics. (For example, I use curly braces against 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 really want to use string interpolation or escaping, otherwise I use single quotes. Thus, when I see the line, I can immediately say that there is no funny thing, and there is no hidden code inside it.

I am pragmatic. I prefer "It a string!" more 'It\ a string!' or %q[It a string!] .

+5
source share

What you probably already know:

  • Single quotes are just fine for simple strings.
  • If you need to evaluate something inside a string, you will need double quotes.

There is no significant difference in performance .

Using double quotes is useful, so you can use apostrophes without worrying about avoiding them inside the string, thereby making the string “prettier” in the code. Think of "Don't do that" vs 'Don\'t do that'

There is the thought that you should never run away in lines . If you need single quotes and double quotes inside your string, you better use heredoc or flexible quotes. In the end, I would give this guide what you need to use when coding, if evaluating the ruby ​​code inside the string is not a problem.

+12
source share

All Articles