I have a requirement to programmatically edit YAML files in Ruby, and I need to also retain the enclosing quote characters unfortunately. Being able to retain the comments too would be a bonus.
That is to say if I have a file:
---
foo: 'bar'
or
---
foo: "bar"
My script must not write it back as:
---
foo: bar
And as mentioned, ideally I need to preserve comments too.
Without going down the path of just treating the whole file as a stream of text, is there any convenient way to solve one or both of these problems?
For most scalars you don't need any quotes at all, but if you need to define some piece of data which contains characters that could be mistaken with YAML syntax you need to quote it in either double " or single ' quotes for the YAML file to stay valid.
Create a file from the YAML URL Now click on these YAML samples. Once this link is open, use save as functionality of the browser and save. It will generate YAML file and save it on your device.
Use quotes in YAML if your value includes special characters. For example, these special characters may require quotes: {, }, [, ], ,, &, :, *, #, ?, |. -, <. >, =, !, %, @, \. It is not necessary to use quotes when a single special character is surrounded by spaces, for example, * with spaces on both sides.
At the time of writing, it appears this is impossible to implement in Ruby, unless you are prepared to write your own YAML parser. I investigated other languages including Perl and Python, and found there is a Python Library called Ruamel that can do this - or more accurately, it will be able to do this when all of its bugs are fixed! So I have re-written my application in Python. See also this answer here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With