2

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

2
  • what about default values in case if attribute missing? Commented Apr 24, 2016 at 16:39
  • I'd just want it to be empty for that value/cell in that case Commented Apr 24, 2016 at 16:43

1 Answer 1

2

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
  end
end

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.