2

给定用于本地化的简单 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 文件以供进一步处理。(注释将作为外部工具识别键的标签)。

4

1 回答 1

0
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
于 2013-06-20T15:49:06.417 回答