Ruby:将转义字符串写入YAML
发布时间:2020-12-17 04:26:11 所属栏目:百科 来源:网络整理
导读:下列… require 'yaml'test = "I'm a bd string"File.open('test.yaml','w') do |out| out.write(test.to_yaml)end ……输出…… --- this is a bd string 我怎样才能输出它 --- 'this is a bd string' ??? 解决方法 如果要在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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Swift 全功能的绘图板开发
- c# – System.Web.HttpException:不能在DropDownList中选择
- ruby-on-rails – 错误:无法构建gem原生扩展
- c# – Thread.Sleep或Thread.Timer挂系统?
- 如何在PostgreSQL / pgAdmin III中将bytea数据作为十六进制
- c# – 垃圾收集器是否隐式使用析构函数方法,并配置开发人员
- 循环中Swift样式的多个增量
- Flash游戏之文字游戏--《打字测试》部分感想
- ruby-on-rails – 使用Heroku更改资产编译位置的正确程序
- ruby-on-rails – Rails Devise Action Cable