convert array of hashes to csv file

后端 未结 3 762
名媛妹妹
名媛妹妹 2021-02-02 11:36

How do you convert an array of hashes to a .csv file?

I have tried

    CSV.open(\"data.csv\", \"wb\") do |csv|
      @data.to_csv
    end
3条回答
  •  余生分开走
    2021-02-02 12:00

    Try this:

    CSV.open("data.csv", "wb") do |csv|
      @data.each do |hash|
        csv << hash.values
      end
    end
    

    If you want the first line of the CSV to contain the keys of the hash (kind of like a header), simply do:

    CSV.open("data.csv", "wb") do |csv|
      csv << @data.first.keys # adds the attributes name on the first line
      @data.each do |hash|
        csv << hash.values
      end
    end
    

    Please read the comment of @cgenco below: He wrote a monkey patch for the Array class.

提交回复
热议问题