Ruby:将转义字符串写入 YAML [英] Ruby: Write escaped string to YAML

查看:28
本文介绍了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 对其进行转义:

If you want to store an escaped string in YAML, escape it using #inspect before you convert it to YAML:

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 不会引用字符串.如果字符串包含不带引号存储它会丢失的内容,它会引用字符串 - 例如周围的引号字符或尾随或前导空格:

YAML doesn't quote strings unless it has to. It quotes strings if they include things that it would miss if it stored it unquoted - like surrounding quote characters or trailing or leading spaces:

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 文件中引用的字符串,那对我来说很糟糕.

However, as a YAML consumer, whether the string is quoted shouldn't matter to you. You should never be parsing the YAML text yourself - leave that to the libraries. If you need the string to be quoted in the YAML file, that smells bad to me.

无论你的字符串中是否有 '&',YAML 都会保留该字符串:

It doesn't matter whether your strings have '&'s in them, YAML will preserve the string:

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

这篇关于Ruby:将转义字符串写入 YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆