可以使用Ruby的YAML模块嵌入注释吗?

to_yaml方法产生了很好的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 

对我来说好处是没有重复(例如,’client:’只指定一次),数据和注释在一起,源可以作为YAML输出,数据结构(在conf中可用)可用于使用。

您可以对所有插入执行字符串替换:

 require 'yaml' source = { :client => 'host4.example.com', :server => '192.168.222.222', }.to_yaml substitution_list = { /:client:/ => "# hostname or IP address of client\n:client:", /:server:/ => "# hostname or IP address of server\n:server:" } substitution_list.each do |pattern, replacement| source.gsub!(pattern, replacement) end puts source 

输出:

 --- # hostname or IP address of client :client: host4.example.com # hostname or IP address of server :server: 192.168.222.222 

像这样的东西:

 my_hash = {a: 444} y=YAML::Stream.new() y.add(my_hash) y.emit("# this is a comment") 

当然,您需要自己遍历输入哈希,并根据需要add()emit() 。 您可以查看to_yaml方法的来源以快速to_yaml