3

I'm converting a hash to yaml in ruby but it adds : to keys: For example:

:name: "Name"
:value: "Value"

If there a way to avoid and just output:

name: "Name"
value: "Value"

I can do this easily with gsub, But just curious

Anthon
  • 69,918
  • 32
  • 186
  • 246
kotyara85
  • 305
  • 3
  • 12

1 Answers1

6

If you use string keys you won't get those prefixes. That's what happens when you serialize something with symbol keys.

In Rails or using ActiveSupport you can call deep_stringify_keys to convert them all prior to a YAML.dump.

Otherwise YAML is just trying to serialize and de-serialize as exactly as it can. A restored file with :name: x has { :name => 'x' } as the resulting data.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • There are pure Ruby ways to do this as well. See [this question](https://stackoverflow.com/q/8379596/3784008) and [this answer in particular](https://stackoverflow.com/a/46978937/3784008). – anothermh Nov 01 '18 at 00:26
  • 4
    with ruby 2.5 you can use `the_hash.transform_keys(&:to_s)` – max pleaner Nov 01 '18 at 03:01