Ruby:将转义字符串写入YAML

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ruby:将转义字符串写入YAML相关的知识,希望对你有一定的参考价值。

下列...

require 'yaml'
test = "I'm a b&d string"
File.open('test.yaml', 'w') do |out|
  out.write(test.to_yaml)
end

......输出......

--- this is a b&d string

我怎样才能输出它

--- 'this is a b&d string'

???

答案

如果要在YAML中存储转义字符串,请在将其转换为YAML之前使用#inspect将其转义:

irb> require 'yaml'
=> true
irb> str = %{This string's a little complicated, but it "does the job" (man, I hate scare quotes)}
=> "This string's a little complicated, but it "does the job" (man, I hate scare quotes)"
irb> puts str
This string's a little complicated, but it "does the job" (man, I hate scare quotes)
=> nil
irb> puts str.inspect
"This string's a little complicated, but it "does the job" (man, I hate scare quotes)"
=> nil
irb> puts str.to_yaml
--- This string's a little complicated, but it "does the job" (man, I hate scare quotes)
=> nil
irb> puts str.inspect.to_yaml
--- ""This string's a little complicated, but it \"does the job\" (man, I hate scare quotes)""
=> nil

除非必须,否则YAML不引用字符串。它引用了字符串,如果它们包含了如果它不加引号地存储它将会遗漏的东西 - 比如周围的引号字符或尾随或前导空格:

irb> puts (str + " ").to_yaml
--- "This string's a little complicated, but it "does the job" (man, I hate scare quotes) "
=> nil
irb> puts %{"#{str}"}.to_yaml
--- ""This string's a little complicated, but it "does the job" (man, I hate scare quotes)""
=> nil
irb> puts (" " + str).to_yaml
--- " This string's a little complicated, but it "does the job" (man, I hate scare quotes)"
=> nil

但是,作为YAML消费者,是否引用字符串对您来说无关紧要。你永远不应该自己解析YAML文本 - 把它留给库。如果你需要在YAML文件中引用字符串,那对我来说闻起来很糟糕。

你的字符串中是否包含“&”并不重要,YAML会保留字符串:

irb> test = "I'm a b&d string"
=> "I'm a b&d string"
irb> YAML::load(YAML::dump(test))
=> "I'm a b&d string"
irb> YAML::load(YAML::dump(test)) == test
=> true
另一答案

根据YAML 1.2 Specification,JSON文档是有效的YAML文档。

此修订的主要目标是使YAML符合JSON作为官方子集。

因此,有效的JSON字符串是有效的YAML字符串。

require 'json'
'my string'.to_json  # => produces a valid YAML string

这对于富含ERB语法的YAML文件非常有用,其中string.to_yaml在许多情况下不起作用。

例:

# openvpn.yml.erb
openvpn:
  cert: <%= ENV.fetch('OPENVPN_CERT').to_json %>
  key: <%= ENV.fetch('OPENVPN_KEY').to_json %>

以上是关于Ruby:将转义字符串写入YAML的主要内容,如果未能解决你的问题,请参考以下文章

如何将带有前导零的数字字符串转储为 yaml-cpp 中的有效 yaml 字符串?

将 Ruby 哈希转换为 YAML

Airbnb案例:Ruby on Rails YAML格式化字符串时导致的远程代码执行

将 Ruby 哈希转换为 JSON(不带转义字符)

SpringBoot Yaml 配置 特殊字符转义

rime 配置 怎么写 yaml 转义符