YAML: Do I need quotes for strings in YAML?

Alexander picture Alexander · Oct 1, 2013 · Viewed 184.8k times · Source

I am trying to write a YAML dictionary for internationalisation of a Rails project. I am a little confused though, as in some files I see strings in double-quotes and in some without. A few points to consider:

  • example 1 - all strings use double quotes;
  • example 2 - no strings (except the last two) use quotes;
  • the YAML cookbook says: Enclosing strings in double quotes allows you to use escaping to represent ASCII and Unicode characters. Does this mean I need to use double quotes only when I want to escape some characters? If yes - why do they use double quotes everywhere in the first example - only for the sake of unity / stylistic reasons?
  • the last two lines of example 2 use ! - the non-specific tag, while the last two lines of the first example don't - and they both work.

My question is: what are the rules for using the different types of quotes in YAML?

Could it be said that:

  • in general, you don't need quotes;
  • if you want to escape characters use double quotes;
  • use ! with single quotes, when... ?!?

Answer

Mark Berry picture Mark Berry · Mar 6, 2014

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'