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,I hate scare quotes)
=> nil
irb> puts str.inspect
"This string's a little complicated,I hate scare quotes)"
=> nil
irb> puts str.to_yaml
--- This string's a little complicated,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,I hate scare quotes) "
=> nil
irb> puts %{"#{str}"}.to_yaml
--- "\"This string's a little complicated,I hate scare quotes)\""
=> nil
irb> puts (" " + str).to_yaml
--- " This string's a little complicated,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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...