How to save a hash into a CSV

前端 未结 7 1559
名媛妹妹
名媛妹妹 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:54

    CSV can take a hash in any order, exclude elements, and omit a params not in the HEADERS

    require "csv"
    HEADERS = [
      'dog',
      'cat',
      'donkey'
    ]
    
    def write_file
    
      CSV.open("data.csv", "wb", :headers => HEADERS, :write_headers => true) do |csv|
        csv << { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
        csv << { 'dog' => 'canine'}
        csv << { 'cat' => 'feline', 'dog' => 'canine', 'donkey' => 'asinine' }
        csv << { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine', 'header not provided in the options to #open' => 'not included in output' }
      end
    end
    
    write_file # => 
    # dog,cat,donkey
    # canine,feline,asinine
    # canine,,
    # canine,feline,asinine
    # canine,feline,asinine
    

    This makes working with the CSV class more flexible and readable.

提交回复
热议问题