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
关于ruby - Ruby 的 YAML 模块可以用来嵌入评论吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14149570/