为什么我的Ruby脚本在输出到终端时不会评估YAML数据中的ANSI转义字符?

huangapple go评论73阅读模式
英文:

Why are the ANSI escape chars in this YAML data not being evaluated when output to terminal by my Ruby script?

问题

我有这个YAML数据:

data.yml

game:
  welcome: 欢迎来到\e[34m您的\e[0m新国际象棋游戏玩家。\n\n

我可以成功访问它:

puts data['game']['welcome']

然而,当输出到终端时,ANSI转义字符格式和换行格式都不起作用。它只是将所有字符都文字地打印出来。我已经尝试/检查过:

  • 终端正在使用UTF-8编码,当直接在Ruby程序中使用字符串字符时,确实可以打印ANSI转义格式。
  • 尝试使用另一个\字符来转义转义字符,例如 \e[34m你的\e[0m。这不起作用。

有什么想法如何让这个工作?谢谢。

英文:

I have this YAML data:

data.yml

game:
  welcome: Welcome to \e[34myour\e[0m new chess game players.\n\n

which I am successfully accessing with:

puts data['game']['welcome']

however when output to terminal neither the ansi escape character formatting nor the newline formatting is working. It just prints out all of the characters literally. I have tried/checked:

  • terminal is using UTF-8 encoding and does print ansi escape formatting when directly used on string characters on a ruby programme.
  • tried escaping the escape characters with another \ character, e.g. \e[34myour\e[0m. This doesn't work.

Any ideas how I might be able to get this working? Thanks

答案1

得分: 1

YAML 只允许在双引号标量中使用转义字符序列。请参阅 YAML 规范的 [粗斜体 强调部分] 第 5.7 节 转义字符

> # 5.7. 转义字符
> 所有不可打印字符必须进行转义。YAML 转义序列使用大多数现代计算机语言通用的“\”表示法。每个转义序列必须解析为相应的 Unicode 字符。原始转义序列是一项呈现细节,不应用于传达内容信息。
>
> 请注意,转义序列仅在双引号标量中解释。在所有其他标量样式中,\”字符没有特殊含义,且不可打印字符不可用

英文:

YAML only allows escape character sequences in double-quoted scalars. See section 5.7 Escaped Characters of the YAML specification [bold italic emphasis mine]:

> # 5.7. Escaped Characters
> All non-printable characters must be escaped. YAML escape sequences use the “\” notation common to most modern computer languages. Each escape sequence must be parsed into the appropriate Unicode character. The original escape sequence is a presentation detail and must not be used to convey content information.
>
> Note that escape sequences are only interpreted in double-quoted scalars. In all other scalar styles, the “\” character has no special meaning and non-printable characters are not available.

huangapple
  • 本文由 发表于 2023年6月2日 05:19:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定