以编程方式向 YAML 添加注释

编程入门 行业动态 更新时间:2024-10-26 08:34:43
本文介绍了以编程方式向 YAML 添加注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

鉴于用于本地化的简单 YAML 文件:

Given the simple YAML file for localisation:

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

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

How can I add a comment to the end of line for some key programmatically in Ruby? I need to get something like:

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 文件以供进一步处理.(评论将作为外部工具识别键的标签).

Are there any other ways (may be using Linux sed) to accomplish this? My reason is to prepare the YAML file for further processing. (comments will act as labels for external tool to identify keys).

推荐答案

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

更多推荐

以编程方式向 YAML 添加注释

本文发布于:2023-11-12 18:44:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注释   方式   YAML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!