简体   繁体   中英

How to update the yaml root key in ruby

I have a requirement to compare the yaml files to identify the differences in it and for that i need yaml files to start with same root key. Is it possible to update the yaml root key in ruby? (Note: Not the value in the yml file)

Yaml file example:

person:
  name: abc
  age: 10
  address: xyz

My requirement is to update the yaml file as below.

student:
  name: abc
  age: 10
  address: xyz

Thanks in advance for help!!!

I am not 100% sure what you are looking for but once you load the yaml, you end up with a ruby hash. You can then just create a new hash with a new name for the root key.

For example this:

require 'yaml'

input = 
"person:
  name: abc
  age: 10
  address: xyz"

obj = YAML.load(input)
new_obj = {"student" => obj["person"]}
output = YAML.dump(new_obj)
puts output

will print:

---
student:
  name: abc
  age: 10
  address: xyz

If for whatever reason you don't want the doc header "---" you can remove it with.

no_header = output.split("\n").drop(1).join("\n")
puts no_header

Which will print:

student:
  name: abc
  age: 10
  address: xyz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM