to_yaml方法会生成很好的YAML输出,但我想在某些元素之前包含注释行。有没有办法做到这一点?可以使用Ruby的YAML模块来嵌入注释吗?
例如,我想制作:
# hostname or IP address of client
client: host4.example.com
# hostname or IP address of server
server: 192.168.222.222
从类似于:
{
:client => 'host4.example.com',
:server => '192.168.222.222',
}.to_yaml
...但我不知道如果YAML模块甚至有一种方式来完成。
更新:我最终没有使用正则表达式插入注释的解决方案,因为它需要从注释中分离数据。对我来说,最简单,最易懂的解决方案是:
require 'yaml'
source = <<SOURCE
# hostname or IP address of client
client: host4.example.com
# hostname or IP address of server
server: 192.168.222.222
SOURCE
conf = YAML::load(source)
puts source
对我的好处是没有重复(例如,“客户:”只指定一次),数据和评论在一起,来源可作为YAML输出,并且数据结构(在conf中可用)可供使用。
你尝试过什么?是什么让你觉得它不起作用? http://yaml.org/spec/current.html#id2509980 –
增加了额外的细节。 – sutch