Convert Ruby Hash into YAML

You can use the to_yaml method on a hash for this I believe after you require yaml


You can use YAML.dump:

YAML.dump(a: 2, b: 1)
=> "---\n:a: 2\n:b: 1\n

One advantage of YAML.dump over to_yaml is that it's easier to infer what the code is doing because most people read from left to right.


Here's how I'd do it:

require 'yaml'

HASH_OF_HASHES = {
  "hostname1.test.com"=> {"public"=>"51", "private"=>"10"},
  "hostname2.test.com"=> {"public"=>"192", "private"=>"12"}
}

ARRAY_OF_HASHES = [
  {"hostname1.test.com"=> {"public"=>"51", "private"=>"10"}},
  {"hostname2.test.com"=> {"public"=>"192", "private"=>"12"}}
]

puts HASH_OF_HASHES.to_yaml
puts
puts ARRAY_OF_HASHES.to_yaml

Which outputs:

---
hostname1.test.com:
  public: '51'
  private: '10'
hostname2.test.com:
  public: '192'
  private: '12'

---
- hostname1.test.com:
    public: '51'
    private: '10'
- hostname2.test.com:
    public: '192'
    private: '12'

The Object class has a to_yaml method. I used that and it generated the YAML file correctly.

No, it doesn't.

This is from a freshly opened IRB session:

Object.instance_methods.grep(/to_yaml/)
=> []
require 'yaml'
=> true
Object.instance_methods.grep(/to_yaml/)
=> [:psych_to_yaml, :to_yaml, :to_yaml_properties]

Tags:

Ruby

Hash

Yaml