Home > database >  How to update the yaml root key in ruby
How to update the yaml root key in ruby

Time:04-04

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!!!

CodePudding user response:

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
  • Related