在 ruby​​ on rails 中更新 yaml 文件的键值 [英] Update value of key of a yaml file in ruby on rails

查看:37
本文介绍了在 ruby​​ on rails 中更新 yaml 文件的键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些键值的 yml 文件.

I have a yml file with some key value.

age: 24
Name: XYZ

我想要代码将Name"键的值从 XYZ 更新为 ABC?我该怎么做?

I want code to update the value of "Name" key from XYZ to ABC? How can i do it?

推荐答案

    require 'yaml'
    data = YAML.load_file "path/to/yml_file.yml"
    data["Name"] = ABC
    File.open("path/to/yml_file.yml", 'w') { |f| YAML.dump(data, f) }

它将写入 yml 文件.如果文件中不存在指定的键(名称"),它将写入新的键值,否则现有的键值将被替换.

It will write into yml file. If specified key ("Name") is not present in file, it will write new key value othrwise the existing one will be replaced.

这篇关于在 ruby​​ on rails 中更新 yaml 文件的键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆