Skip to content

Instantly share code, notes, and snippets.

@christiangenco
Created June 6, 2014 04:26
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save christiangenco/8acebde2025bf0891987 to your computer and use it in GitHub Desktop.
Save christiangenco/8acebde2025bf0891987 to your computer and use it in GitHub Desktop.
Ruby hash array to CSV
class Array
def to_csv(csv_filename="hash.csv")
require 'csv'
CSV.open(csv_filename, "wb") do |csv|
csv << first.keys # adds the attributes name on the first line
self.each do |hash|
csv << hash.values
end
end
end
end
# ex: [{a: 1, b: 2}, {a: 3, b: 4}].to_csv("hash.csv")
@michaelmagistro
Copy link

Hey thanks, this is a super useful little script. I used it to convert an array of hashes into a csv file.

For instance, this:

[
    [0] {
                     :id => "1",
        :status => "No",
             :date => "3/18/2014",
           :grade => "b",
           :count => "28",
           :group => "Suzie"
    },
    [1] {
                     :id => "2",
        :status => "Yes",
             :date => "3/14/2016",
           :grade => "c",
           :count => "89",
           :group => "Jack"
    },
    [2] {
                     :id => "2",
        :status => "Yes",
             :date => "3/17/2016",
           :grade => "d",
           :count => "38",
           :group => "John"
    }
]

Into this:

id,status,date,grade,count,group
1,No,3/18/2014,b,28,Suzie
2,Yes,3/14/2016,c,89,Jack
2,Yes,3/17/2016,d,38,John

@jasonben
Copy link

If the hashes aren't uniform then you will end up with data in the wrong columns. You should use values_at instead:

def to_csv(csv_filename = "hash.csv")
  require "csv"
  CSV.open(csv_filename, "wb") do |csv|
    keys = first.keys
    # header_row
    csv << keys
    self.each do |hash|
      csv << hash.values_at(*keys)
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment