Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Ruby Hash into YAML

Tags:

ruby

yaml

hash

I need to convert a hash like the one provided below into readable YAML. It looks like I can feed YAML::load a string, but I think I need to convert it first into something like this:

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

I'm not sure exactly how to do that conversion into that string effectively though.

I looked through the HASH documentation and couldn't find anything for to_yaml. I found it by searching for to_yaml which becomes available when you require yaml. I also tried to use the Enumerable method collect but got confused when I needed to iterate through the value (another hash).

I'm trying to use "Converting hash to string in Ruby" as a reference. My thought was then to feed that into YAML::load and that would generate the YAML I wanted.

like image 569
Shail Patel Avatar asked Jul 10 '13 16:07

Shail Patel


2 Answers

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] 
like image 144
the Tin Man Avatar answered Sep 22 '22 19:09

the Tin Man


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

like image 43
Shail Patel Avatar answered Sep 24 '22 19:09

Shail Patel