Adding comment to YAML programmatically

前端 未结 1 1047
情深已故
情深已故 2021-01-22 11:22

Given the simple YAML file for localisation:

root:
  label: \'Test\'
  account: \'Account\'
  add: \'Add\'
  local_folder: \'Local folder\'
  remote_folder: \'Re         


        
1条回答
  •  生来不讨喜
    2021-01-22 11:43

    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
    

    EDIT

    more programmatically:

    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
    

    0 讨论(0)
提交回复
热议问题