rubyyaml

How do I force double-quotes when dumping YAML?


I have a small script to automate some things in YAML files.

I read the original YAML file and convert it into a hash and then dump it to the file after modifying it:

File.open(output_file, "w") do |out|
  YAML.dump(modified_hash, out)
end

That works fine, but it removes double-quotes around the string if they aren't needed. That's valid YAML, but it doesn't look very nice.

I could add a space at the end of every string to force single-quotes, but I'm not too happy with that. Is there any way of forcing double-quotes around strings?


Solution

  • I found a solution, it's weird, but it works.

    To force single quotes, I went through the hash and appended "foobar " (note the space) to every value. After using YAML.dump, I opened the file again and replaced "foobar " with empty string.

    To force double quotes, I found that appending "foo \nbar" does the job. Again, I then open the file and replace "foo \\nbar" with empty string. Weird, but works.

    Note that you probably want to chose something less likely used than foobar.