How to save a hash into a CSV

前端 未结 7 1570
名媛妹妹
名媛妹妹 2020-12-08 04:26

I am new in ruby so please forgive the noobishness.

I have a CSV with two columns. One for animal name and one for animal type. I have a hash with all the keys being

7条回答
  •  感动是毒
    2020-12-08 04:41

    If you want column headers and you have multiple hashes:

    require 'csv'
    hashes = [{'a' => 'aaaa', 'b' => 'bbbb'}]
    column_names = hashes.first.keys
    s=CSV.generate do |csv|
      csv << column_names
      hashes.each do |x|
        csv << x.values
      end
    end
    File.write('the_file.csv', s)
    

    (tested on Ruby 1.9.3-p429)

提交回复
热议问题