以编程方式向YAML添加注释

给定简单的YAML文件进行本地化:

root: label: 'Test' account: 'Account' add: 'Add' local_folder: 'Local folder' remote_folder: 'Remote folder' status: 'Status' subkey: 'Some value' 

如何在Ruby中以编程方式为某些键添加注释到行尾? 我需要得到类似的东西:

 root: label: 'Test' account: 'Account' add: 'Add' local_folder: 'Local folder' #Test comment remote_folder: 'Remote folder' status: 'Status' subkey: 'Some value' #Test comment 

有没有其他方法(可能使用Linux sed)来实现这一目标? 我的理由是准备YAML文件以进行进一步处理。 (注释将作为外部工具的标签来识别键)。

 require 'yaml' str = <<-eol root: label: 'Test' account: 'Account' add: 'Add' local_folder: 'Local folder' remote_folder: 'Remote folder' status: 'Status' subkey: 'Some value' eol h = YAML.load(str) h["root"]["local_folder"] = h["root"]["local_folder"] + " !Test comment" h["root"]["subkey"] = h["root"]["subkey"] + " !Test comment" puts h.to_yaml # >> --- # >> root: # >> label: Test # >> account: Account # >> add: Add # >> local_folder: Local folder !Test comment # >> remote_folder: Remote folder # >> status: Status # >> subkey: Some value !Test comment 

编辑

更多编程:

 require 'yaml' str = <<-eol root: label: 'Test' account: 'Account' add: 'Add' local_folder: 'Local folder' remote_folder: 'Remote folder' status: 'Status' subkey: 'Some value' eol h = YAML.load(str) %w(local_folder subkey).each {|i| h["root"][i] = h["root"][i] + " !Test comment" } puts h.to_yaml # >> --- # >> root: # >> label: Test # >> account: Account # >> add: Add # >> local_folder: Local folder !Test comment # >> remote_folder: Remote folder # >> status: Status # >> subkey: Some value !Test comment