How to save a hash into a CSV

前端 未结 7 1563
名媛妹妹
名媛妹妹 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 05:00

    Lets we have a hash,

    hash_1 = {1=>{:rev=>400, :d_odr=>3}, 2=>{:rev=>4003, :d_price=>300}}
    

    The above hash_1 having keys as some id 1,2,.. and values to those are again hash with some keys as (:rev, :d_odr, :d_price). Suppose we want a CSV file with headers,

    headers = ['Designer_id','Revenue','Discount_price','Impression','Designer ODR']
    

    Then make a new array for each value of hash_1 and insert it in CSV file,

    CSV.open("design_performance_data_temp.csv", "w") do |csv|
     csv << headers
     csv_data = []
     result.each do |design_data|
      csv_data << design_data.first
      csv_data << design_data.second[:rev] || 0
      csv_data << design_data.second[:d_price] || 0
      csv_data << design_data.second[:imp] || 0
      csv_data << design_data.second[:d_odr] || 0
      csv << csv_data
      csv_data = []
     end
    end
    

    Now you are having design_performance_data_temp.csv file saved in your corresponding directory. Above code can further be optimized.

提交回复
热议问题