convert array of hashes to csv file

后端 未结 3 761
名媛妹妹
名媛妹妹 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:08

    CSV is smart enough to deal with the non-uniform hashes for you. See the code for CSV::Writer#<<

    So, this works, and is a bit simpler than the above examples:

    CSV.open("data.csv", "wb", {headers: @data.first.keys} ) do |csv|
      @data.each do |hash|
        csv << hash
      end
    end
    

提交回复
热议问题