本文翻译自:Do I need quotes for strings in YAML?
I am trying to write a YAML dictionary for internationalization of a Rails project. 我正在尝试编写有关Rails项目国际化的YAML字典。 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; 示例1-所有字符串都使用双引号;
- example 2 - no strings (except the last two) use quotes; 示例2-没有字符串(最后两个除外)使用引号;
- the YAML cookbook says: Enclosing strings in double quotes allows you to use escapings to represent ASCII and Unicode characters. YAML食谱说: 用双引号引起来的字符串使您可以使用转义符来表示ASCII和Unicode字符。 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
!
示例2的最后两行使用!
- 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? 我的问题是:在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... ?!? 用单引号括起来,何时...?!?
#1楼
参考:https://stackoom.com/question/1IBMO/我需要在YAML中为字符串加引号吗
#2楼
After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation: 在对问题中引用的YAML食谱进行简短回顾并进行了一些测试之后,以下是我的解释:
- In general, you don't need quotes. 通常,您不需要引号。
- Use quotes to force a string, eg if your key or value is
10
but you want it to return a String and not a Fixnum, write'10'
or"10"
. 使用引号强制输入字符串,例如,如果您的键或值是10
但您希望它返回字符串而不是Fixnum,则输入'10'
或"10"
。 - Use quotes if your value includes special characters, (eg
:
,{
,}
,[
,]
,,
,&
,*
,#
,?
,|
,-
,<
,>
,=
,!
,%
,@
,\\
). 使用引号如果值包含特殊字符(例如:
,{
,}
,[
,]
,,
,&
,*
,#
,?
,|
,-
<
,>
,=
,!
,%
,@
,\\
)。 - 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
.'\\n'
将作为字符串\\n
返回。 - Double quotes parse escape codes. 双引号解析转义码。
"\\n"
would be returned as a line feed character."\\n"
将作为换行符返回。 - The exclamation mark introduces a method, eg
!ruby/sym
to return a Ruby symbol. 感叹号引入了一种方法,例如!ruby/sym
以返回Ruby符号。
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: “是”和“否”应用引号引起来(单引号或双引号),否则它们将被解释为TrueClass和FalseClass值:
en:
yesno:
'yes': 'Yes'
'no': 'No'