Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving data from a hash to a YAML file

When I try to save data from a hash to a file, I only get the last line of my hash. What is going wrong?

h= {}
infoArray.zip(href) {|a,b| h[a.to_sym] = b } # i convert two array in hash 

File.open("lib/alreadyPass.yml","w") do |file|
       file.write h.to_yaml
  end 

An example of my hash is:

{:"client-1.domaine.net"=>"www.client-1.domaine.net/index.html/xxxxxx"}

{:"client-2.domaine.net"=>"www.client-2.domaine.net/index.html/xxxxxx"}

And the output YAML file I am getting is:

---
:client-1.domaine.net:
- www.client-1.domaine.net/index.html/xxxxxx
like image 206
user2912390 Avatar asked Mar 20 '23 01:03

user2912390


1 Answers

The right way would be like this:

require 'yaml'
array_of_hashes = [{:"client-1.domaine.net"=>"www.client-1.domaine.net/index.html/xxxxxx"},{:"client-2.domaine.net"=>"www.client-2.domaine.net/index.html/xxxxxx"}]

File.open("lib/yamlfile.yml","w") do |file|
   file.write array_of_hashes.to_yaml
end 

This works with a hash of hashes as well...

like image 115
Oliver Zeyen Avatar answered Mar 23 '23 17:03

Oliver Zeyen