gpt4 book ai didi

Ruby:将转义字符串写入 YAML

转载 作者:数据小太阳 更新时间:2023-10-29 06:55:57 27 4
gpt4 key购买 nike

以下...

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

关于Ruby:将转义字符串写入 YAML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/715818/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com