convert array of hashes to csv file

后端 未结 3 760
名媛妹妹
名媛妹妹 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 11:53

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

    CSV.open("data.csv", "wb") do |csv|
      keys = @data.first.keys
      csv << keys
      @data.each do |hash|
        csv << hash.values_at(*keys)
      end
    end
    

提交回复
热议问题