How to save a hash into a CSV How to save a hash into a CSV ruby ruby

How to save a hash into a CSV


If you want column headers and you have multiple hashes:

require 'csv'hashes = [{'a' => 'aaaa', 'b' => 'bbbb'}]column_names = hashes.first.keyss=CSV.generate do |csv|  csv << column_names  hashes.each do |x|    csv << x.values  endendFile.write('the_file.csv', s)

(tested on Ruby 1.9.3-p429)


Try this:

require 'csv'h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }CSV.open("data.csv", "wb") {|csv| h.to_a.each {|elem| csv << elem} }

Will result:

1.9.2-p290:~$ cat data.csv dog,caninecat,felinedonkey,asinine


I think the simplest solution to your original question:

def write_file  h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }  CSV.open("data.csv", "w", headers: h.keys) do |csv|    csv << h.values  endend

With multiple hashes that all share the same keys:

def write_file  hashes = [ { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' },             { 'dog' => 'rover', 'cat' => 'kitty', 'donkey' => 'ass' } ]  CSV.open("data.csv", "w", headers: hashes.first.keys) do |csv|    hashes.each do |h|      csv << h.values    end  endend