Splashlin Splashlin - 6 months ago 14
Ruby Question

Create CSV of Array of Hashes with Different Keys

I have an array of hashes that largely contain the same values; but, some of the hashes have additional key value pairs that the others don't. For example the array looks something like

example_array = [{"make" => "nissan", "model" => "altima"}, {"make" => "nissan", "model" => "maxima", "price" => "20,000"}]

My issue comes that I'm trying to export this array of hashes into a CSV. I can't figure out how to

  1. Make sure that the headers of the file has a column/key for every possible key that exists in the array

  2. Make sure that values end up in the correct column

Any help would be greatly appreciated


You can write it like:

require 'csv'

headers = example_array.inject([]) {|res, h| h.keys | res} #all possible headers
#=> ["make", "model", "price"]
rows = example_array.map {|h| h.values_at(*headers)}
#=> [["nissan", "altima", nil], ["nissan", "maxima", "20,000"]]
CSV.generate do |csv|
  csv << headers
  rows.each do |row|
    csv << row

If you want to write csv in file, just write CSV.open("myfile.csv", "w") instead of CSV.generate.